/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import fr.gouv.finances.cp.xemelios.common.config.DocumentModel;
import fr.gouv.finances.cp.xemelios.common.config.EtatModel;
import fr.gouv.finances.cp.xemelios.data.impl.sqlconfig.PersistenceConfigDeriveParser;
import fr.gouv.finances.cp.xemelios.data.impl.sqlconfig.PersistenceConfigParser;
import fr.gouv.finances.cp.xemelios.data.impl.sqlconfig.TPersistenceConfig;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;

/**
 * Provides some services
 * @author chm
 */
public abstract class AbstractDataImpl implements DataImpl {
    
	private final static Logger logger = Logger.getLogger(AbstractDataImpl.class);
	private final Object locker = new Object();
    static protected Map<String,Class> persistenceModels = new HashMap<String,Class>();
    static {
        persistenceModels.put("xemelios-sql",TPersistenceConfig.class);
    }
    protected Map<String,TPersistenceConfig> cachedPersistence = new HashMap<String,TPersistenceConfig>();
    protected File documentConfigDirectory = null;

    public boolean importElement(DocumentModel dm, EtatModel currentEtat, String sourceFileName, String elementName, Document element, int overwriteMode) throws DataAccessException {
        return false;
    }
    public void setDocumentsConfigDirectory(File directory) { this.documentConfigDirectory=directory; }

    public void reset(){
    	cachedPersistence.clear();
    }
    
    public TPersistenceConfig getPersistenceConfig(DocumentModel dm) throws DataConfigurationException {
        TPersistenceConfig pc = cachedPersistence.get(dm.getId());
        long start = System.currentTimeMillis();
        if(pc==null) {
        	synchronized (locker) {
	        	logger.info("Chargement de la configuration "+dm.getTitre());
	            String fileName = dm.getPersistenceConfigFile();
	            File configFile = new File(new File(dm.getBaseDirectory()),fileName);
	            try {
	            	
	            	// .XML => persistence normale
	            	if (fileName.toUpperCase().endsWith(".XML")) {
		            	PersistenceConfigParser handler = new PersistenceConfigParser(dm.getBaseDirectory());
		            	handler.parse(configFile);
		            	pc = (TPersistenceConfig)handler.getMarshallable();
				pc.setBaseDirectory(dm.getBaseDirectory());
		                cachedPersistence.put(dm.getId(),pc);
	            	}
//	            	.EXML => persistence dérivée
	            	else if (fileName.toUpperCase().endsWith(".EXML")) {
                            PersistenceConfigParser handler = new PersistenceConfigParser(dm.getBaseDirectory());
                            String parentDocId = dm.getExtendedDocId();
                            DocumentModel parentConfig = MainWindow.getInstance().getDocModels().getDocumentById(parentDocId);
                            TPersistenceConfig parentPersistConfig = getPersistenceConfig(parentConfig);
                            handler.setInitialData(parentPersistConfig);
                            handler.parse(configFile);
                            pc = (TPersistenceConfig)handler.getMarshallable();
                            pc.setBaseDirectory(dm.getBaseDirectory());
                            cachedPersistence.put(dm.getId(), pc);
	            	}
	            } catch(ParserConfigurationException pcEx) {
	                throw new DataConfigurationException(pcEx);
	            } catch(IOException ioEx) {
	                throw new DataConfigurationException(ioEx);
	            } catch(SAXException saxEx) {
	                throw new DataConfigurationException(saxEx);
	            }
        	}	// synchronized
        }
        return pc;
    }
    
}
