/*
 * Loader.java
 *
 * Created on 14 novembre 2007, 11:08
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */


package fr.gouv.finances.cp.xemelios.common.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

/**
 * Provides helper method to load config files
 * @author chm
 */
public class Loader {
    private static final Logger logger = Logger.getLogger(Loader.class);
    
    /**
     * Loads and returns config files. If config files contains at least one error, returns an empty DocumentsModel.
     * @param repertoires A comma-separated list of directories where to find config files
     * @return DocumentsModel the fully-assembled config
     */
    public static DocumentsModel getDocsInfos(String repertoires) throws SAXException, ParserConfigurationException, IOException {
        DocumentsModel ret = null;
        String[] dirs = repertoires.split(",");
        for(String repertoire:dirs) {
            File dir = new File(repertoire);
            logger.info("Searching " + repertoire);
            if (!dir.exists()) {
                logger.info(repertoire + " does not exists.");
                continue;
            }
            // Fichiers de config
            File[] fichiers = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".XML") && !"build.xml".equals(name);
                }
            });
            if (fichiers == null) {
                logger.info("No file found in " + repertoire);
                return null;
            }
            DocumentsParser dp = new DocumentsParser();
            for (int i = 0; i < fichiers.length; i++) {
                dp.parse(fichiers[i]);
                DocumentsModel dm = (DocumentsModel) dp.getMarshallable();
                if (ret == null) {
                    ret = dm;
                    for(DocumentModel docModel:dm.getDocuments()) {
                        docModel.setBaseDirectory(repertoire);
                    }
                } else {
                    for(DocumentModel docModel : dm.getDocuments()) {
                        docModel.setBaseDirectory(repertoire);
                        ret.addChild(docModel, DocumentModel.QN);
                    }
                }
            }
        }
        for(String repertoire:dirs) {
            // fichiers d�riv�s d'une config
            File dir = new File(repertoire);
            logger.info("Searching " + repertoire);
            if (!dir.exists()) {
                logger.info(repertoire + " does not exists.");
                continue;
            }
            File[] fichiers = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".EXML");
                }
            });
            if (fichiers == null) {
                logger.info("No file found in " + repertoire);
                return null;
            }
            for(File f:fichiers) {
                DocumentsParser dp = new DocumentsParser();
                dp.setInitialData(ret);
                dp.parse(f);
                ret = (DocumentsModel)dp.getMarshallable();
                for(DocumentModel docModel:ret.getDocuments()) {
                    if(docModel.getBaseDirectory()==null)
                        docModel.setBaseDirectory(repertoire);
                }
            }
        }
        return ret;
    }
    
    public static DocumentsModel getDocumentsInfos(String repertoires) throws SAXException, ParserConfigurationException, IOException {
        DocumentsModel ret = getDocsInfos(repertoires);
        try {
            ret.validate();
        } catch(Throwable t) {
            logger.error("while loading config files: "+t);
            ret = new DocumentsModel(DocumentsModel.QN);
        }
        logger.debug("exiting successfully getDocumentsInfos");
        return ret;
    }
    
}
