/*
 * 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(documentConfigDirectory,fileName);
	            File configFile = new File(new File(dm.getBaseDirectory()),fileName);
	            //DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	            try {
	                //DocumentBuilder db = dbf.newDocumentBuilder();
	                //Document doc = db.parse(configFile);
//	                XPathFactory xpf = null;
//	                try {
//	                	xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
//	                } catch(Throwable t) {
//	                	xpf = XPathFactory.newInstance();
//	                }
//	                xpf.setXPathFunctionResolver(new FunctionResolver());
//	                XPath xp = xpf.newXPath();
//	                String xPathExpr = "//layer[@name='"+getLayerName()+"']";
//	                Element layer = (Element)xp.evaluate(xPathExpr,doc,XPathConstants.NODE);
//	                logger.debug("got layer in "+(System.currentTimeMillis()-start)+" ms");
//	                String persitenceModelName = layer.getAttribute("persistence-model");
//	                Class persistClass = persistenceModels.get(persitenceModelName);
//	                if(persistClass==null) throw new DataConfigurationException("Unknown persistence config: "+persitenceModelName);
//	                pc = (PersistenceConfig)persistClass.newInstance();
//	                // provisoire
//	                ((SqlPersistenceConfig)pc).setLayer(layer);
//	                logger.debug("loaded config in "+(System.currentTimeMillis()-start)+" ms");
//	                // provisoire
//	                ((SqlPersistenceConfig)pc).setDocumentsConfigDirectory(documentConfigDirectory);
	            	
	            	// .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")) {
	            		PersistenceConfigDeriveParser pcp = new PersistenceConfigDeriveParser(cachedPersistence,dm.getBaseDirectory());
	            		SAXParserFactory factorySAX = SAXParserFactory.newInstance();
	            		factorySAX.setNamespaceAware(true);
                    		FileInputStream fis = new FileInputStream(configFile);
        			SAXParser parserXml = factorySAX.newSAXParser();
        			parserXml.parse(fis, pcp);
        			fis.close();
        			pc = pcp.getCurrent();
        			// si pc est nul, peut �tre est-ce parce que la configuration dont on d�rive n'est pas encore charg�e; 
        			// on tente alors de la charger et on recommence
        			if (pc == null) {
        				if (pcp.getFileToDerive().toUpperCase().endsWith(".XML")) {
						DocumentModel parentDoc = MainWindow.getInstance().getDocModels().getDocumentById(dm.getExtendedDocId());
            					File tmp = new File(new File(parentDoc.getBaseDirectory()),pcp.getFileToDerive());
        		            		PersistenceConfigParser handler = new PersistenceConfigParser(parentDoc.getBaseDirectory());
        		            		handler.parse(tmp);
        		            		pc = (TPersistenceConfig)handler.getMarshallable();
        		                	cachedPersistence.put(pcp.getDocIdToDerive(),pc);

						// on retente de charger la configuration
						pcp.setCachedPersistence(cachedPersistence);
						fis = new FileInputStream(configFile);
                				parserXml.parse(fis, pcp);
						fis.close();
                				pc = pcp.getCurrent();
                				if (pc != null) {
                					cachedPersistence.put(dm.getId(), pc);
                				}
        	            		}
        			} else {
        				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);
	            }
//	            doJaxB(dm);
        	}	// synchronized
        }
        return pc;
    }
    
//    public void doJaxB(DocumentModel dm) {
//    	long start = System.currentTimeMillis();
//    	try {
//    		JAXBContext ctx = JAXBContext.newInstance("fr.gouv.finances.cp.xemelios.data.impl.jaxb");
//    		Unmarshaller um = ctx.createUnmarshaller();
//    		Object o = um.unmarshal(new File(documentConfigDirectory,dm.getPersistenceConfigFile()));
//    		logger.info(o);
//    	} catch(Exception ex) {
//    		ex.printStackTrace();
//    	}
//    	logger.info("jaxb: "+(System.currentTimeMillis()-start)+" ms");
//    }
}
