/*
 * $Revision: 1.2 $ $Date: 2006/04/25 10:00:11 $
 * Copyright (C) 2004-2006 SUGIMOTO Ken-ichi
 * 作成日: 2004/05/15
 */
package feat2.config;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

import javax.xml.parsers.FactoryConfigurationError;

import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import feat2.FeatException;
import feat2.FileResourceManager;
import feat2.ObjectUtil;

public class ConfigReader {

    private static Log log = LogFactory.getLog(ConfigReader.class);

    /**
     * feat-config.xmlを読み込む。
     * @param appRoot アプリケーションのルートディレクトリ。
     * @param locator feat-config.xmlファイル。
     * @throws FeatException
     * @return FeatConfig
     */
    public static FeatConfig parseFeatConfig(FileLocator appRoot, FileLocator locator) throws FeatException {

        Digester digester = null;
        FeatConfig config = null;

        InputStream in = null;
        try {
            // 設定ファイルの読み込み

            URL rule = ConfigReader.class.getClassLoader().getResource("feat2/rules/feat-config-rules.xml");
            digester = DigesterLoader.createDigester(rule);
            digester.setEntityResolver(new FeatEntityResolver());
            digester.setValidating(true);
            addConverter(digester);

            in = new BufferedInputStream(locator.openInputStream());
            config = (FeatConfig)digester.parse(in);
            config.setAppRootLocator(appRoot);
            config.setConfigFileLocator(locator);

            // Feature設定ファイルの読み込み

            Iterator it = config.getFeatures();
            while( it.hasNext() ) {
                FeatureConfig fc = (FeatureConfig)it.next();
                String featureConfigFilename = fc.getConfigFilename();

                if ( featureConfigFilename != null ) {

                    FileLocator featureConfigLocator = locator.newLocation(featureConfigFilename);

                    FeatureRootConfig feature = parseFeature(featureConfigLocator);

                    fc.setFeatureRoot(feature);
                    fc.setConfigFileLocator(featureConfigLocator);

                }
                else {

                    log.error(FileResourceManager.getInstance().getStringResource("error.config.feature.configFilename.null"));

                }

            }

            // 初期化

            //config.init();
        }
        catch (FactoryConfigurationError ex) {
            throw new FeatException(ex, FeatException.LEVEL_FATAL);
        }
        catch (SAXException ex) {
            throw new FeatException(ex, FeatException.LEVEL_FATAL);
        }
        catch (IOException ex) {
            throw new FeatException(ex, FeatException.LEVEL_FATAL);
        }
        finally {
            if ( in != null ) {
                try {
                    in.close();
                }
                catch (IOException ex) {
                }
            }
        }
        return config;
    }

    /**
     * feature設定ファイルの読み込み。
     * @param config feature設定ファイル。
     * @throws FeatException
     * @return FeatureDeclaration
     */
    //public static FeatureDeclaration parseFeature(FeatureConfig featureConfig) throws FeatException {
    public static FeatureRootConfig parseFeature(FileLocator file) throws FeatException {

        Digester digester = null;
        FeatureRootConfig feature = null;
        InputStream in = null;
        try {
            digester = DigesterLoader.createDigester(ConfigReader.class.getClassLoader().getResource("feat2/rules/feature-config-rules.xml"));
            digester.setEntityResolver(new FeatEntityResolver());
            digester.setValidating(true);
            addConverter(digester);

            in = new BufferedInputStream(file.openInputStream());
            feature = (FeatureRootConfig)digester.parse(in);
        }
        catch (FactoryConfigurationError ex) {
            throw new FeatException(ex, FeatException.LEVEL_FATAL);
        }
        catch (SAXException ex) {
            throw new FeatException(ex, FeatException.LEVEL_FATAL);
        }
        catch (IOException ex) {
            throw new FeatException(ex, FeatException.LEVEL_FATAL);
        }
        finally {
            if ( in != null ) {
                try {
                    in.close();
                }
                catch (IOException ex) {
                }
            }
        }

        return feature;
    }

    /**
     * リソースファイルを読み込む。
     * @param file
     * @return
     * @throws FeatException 読み込みに失敗した
     */
    public static Resources parseResource(FileLocator file) throws FeatException {

        Digester digester = null;
        Resources resourcesDecl = null;
        InputStream in = null;

        try {
            digester = DigesterLoader.createDigester(ConfigReader.class.getClassLoader().getResource("feat2/rules/resource-rules.xml"));
            addConverter(digester);

            /*digester.addObjectCreate("resources", ResourcesDeclaration.class);
            digester.addCallMethod("resources/resource", "addResource", 2);
            digester.addCallParam("resources/resource", 0, "name");
            digester.addCallParam("resources/resource", 1);*/

            in = new BufferedInputStream(file.openInputStream());
            resourcesDecl = (Resources)digester.parse(in);
        }
        catch (IOException ex) {
            throw new FeatException("IOException - "+file, ex, FeatException.LEVEL_ERROR);
        }
        catch (SAXException ex) {
            throw new FeatException("SAXException - "+file, ex, FeatException.LEVEL_ERROR);
        }
        finally {
            if ( in != null ) {
                try {
                    in.close();
                }
                catch (IOException ex) {
                }
            }
        }

        return resourcesDecl;
    }

    private static void addConverter(Digester digester) {

        ConvertUtilsBean convertUtils = digester.getBeanUtils().getConvertUtils();
        ObjectUtil.setFeatConverters(convertUtils);

    }

}

class FeatEntityResolver implements EntityResolver {

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
        if ( systemId.indexOf("feat-config.dtd") > -1 ) {
            return new InputSource(open("feat-config.dtd"));
        }
        else if ( systemId.indexOf("feature-config.dtd") > -1 ) {
            return new InputSource(open("feature-config.dtd"));
        }
        return null;
    }

    private InputStream open(String resourcePath) {
        ClassLoader loader = ConfigReader.class.getClassLoader();
        InputStream in = loader.getResourceAsStream(resourcePath);
        return in;
    }

}
