package org.apache.torque.generator.configuration;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.jar.JarFile;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.torque.generator.configuration.paths.ProjectPaths;
import org.apache.torque.generator.configuration.paths.TorqueGeneratorPaths;

/**
 * Provides InputStreams to read a configuration of a unit of generation from a
 * jar file.
 */
public class ClasspathConfigurationProvider
        extends AbstractConfigurationProvider
{
    /** The logger. */
    private static Log log
            = LogFactory.getLog(ClasspathConfigurationProvider.class);

    /**
     * The paths needed to interact with the enclosing project, not null.
     */
    private ProjectPaths projectPaths;

    /**
     * The internal directory structure of the Torque generator
     * configuration files, not null.
     */
    private TorqueGeneratorPaths configurationPaths;

    /** The prefix if an url points to a file. */
    private static final String FILE_URL_PREFIX = "file:";

    /**
     * Constructor.
     * @param projectPaths the paths needed to interact with the enclosing
     *        project, not null.
     * @param configurationPaths The internal directory structure of the
     *        Torque generator configuration files, not null.
     *
     * @throws NullPointerException if projectPaths or configurationPaths
     *         are null.
     */
    public ClasspathConfigurationProvider(
            ProjectPaths projectPaths,
            TorqueGeneratorPaths configurationPaths)
    {
        super(configurationPaths);
        if (projectPaths == null)
        {
            throw new NullPointerException("projectPaths is null");
        }
        this.projectPaths = projectPaths;
        this.configurationPaths = configurationPaths;
    }

    public String getControlConfigurationLocation()
    {
        return getFileName(
                configurationPaths.getControlConfigurationFile(),
                configurationPaths.getConfigurationDirectory());
    }

    protected String getFileName(
            String name,
            String directory)
    {
        String fileName
                = getConfigResourceBase()
                    + "/"
                    + directory
                    + "/"
                    + name;
        // make double dots work for resources in jar files
        fileName = FilenameUtils.normalizeNoEndSeparator(fileName);
        fileName = FilenameUtils.separatorsToUnix(fileName);
        return fileName;
    }

    protected InputStream getInputStream(
                String name,
                String directory,
                String fileDescription)
            throws ConfigurationException
    {
        String fileName = getFileName(name, directory);

        InputStream inputStream
                = getClass().getClassLoader().getResourceAsStream(
                        fileName);

        if (inputStream == null)
        {
            throw new ConfigurationException(
                    "Could not read " + fileDescription + " file "
                        + fileName
                        + " in classpath");
        }
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        if (log.isDebugEnabled())
        {
            log.debug("Reading " + fileDescription + " file: '"
                    + fileName
                    + "' in classpath");
        }
        return bis;
    }

    public Collection<String> getOutletConfigurationNames()
        throws ConfigurationException
    {
        String outletConfigurationSubdir
                = getConfigResourceBase()
                    + "/"
                    + configurationPaths.getOutletDirectory();
        outletConfigurationSubdir
                = outletConfigurationSubdir.replace('\\', '/');


        URL dirUrl = getClass().getClassLoader().getResource(
                    outletConfigurationSubdir);
        if (dirUrl == null)
        {
            log.error("Could not open Directory "
                    + outletConfigurationSubdir
                    + " in classpath");
            throw new ConfigurationException(
                    "outletConfigurationSubdir not found");
        }
        String dirUrlString = dirUrl.toExternalForm();
        if (dirUrlString.startsWith("jar"))
        {
            String jarFilePath = dirUrl.getFile();
            if (jarFilePath.startsWith(FILE_URL_PREFIX))
            {
                jarFilePath = jarFilePath.substring(FILE_URL_PREFIX.length());
            }
            jarFilePath = jarFilePath.substring(0, jarFilePath.indexOf("!"));
            if (log.isDebugEnabled())
            {
                log.debug("outlet configuration located in jar file"
                        + jarFilePath);
            }
            JarFile jarFile;
            try
            {
                jarFile = new JarFile(jarFilePath);
            }
            catch (IOException e)
            {
                log.error("Could not open jar File "
                        + jarFilePath);
                throw new ConfigurationException(e);
            }

            String outletConfigurationDirectory
                    = dirUrlString.substring(dirUrlString.lastIndexOf("!") + 1);
            if (outletConfigurationDirectory.startsWith("/"))
            {
                outletConfigurationDirectory
                        = outletConfigurationDirectory.substring(1);
            }
            return JarConfigurationProvider.getOutletConfigurationNames(
                    jarFile,
                    outletConfigurationDirectory);
        }
        File directory = new File(dirUrl.getFile());
        if (!directory.exists())
        {
            throw new ConfigurationException(
                    "Could not read outlet directory "
                        + outletConfigurationSubdir
                        + " in classpath; directory URL is "
                        + dirUrl
                        + " file is "
                        + dirUrl.getFile());
        }
        String[] filenames = directory.list();

        List<String> result = new ArrayList<String>();
        for (String filename : filenames)
        {
            File file = new File(filename);
            if (file.isDirectory())
            {
                continue;
            }
            String rawName = file.getName();
            if (!rawName.endsWith(".xml"))
            {
                continue;
            }
            result.add(filename);
        }
        return result;
    }

    /**
     * Gets the resource name for the configuration base directory from the
     * projectPaths.
     *
     * @return the resource name for the configuration base directory,
     *         not null.
     */
    private String getConfigResourceBase()
    {
        String configResourceBase
            = projectPaths.getConfigurationPackage().replace('.', '/');
        return configResourceBase;
    }
}
