/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 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.impl.sqlconfig;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
import fr.gouv.finances.cp.xemelios.common.config.DocumentsDeriveParser;

public class PersistenceConfigDeriveParser extends DefaultHandler {
	private static Logger logger = Logger.getLogger(PersistenceConfigDeriveParser.class);
	
	Map<String,TPersistenceConfig> cachedPersistence = null;
	TPersistenceConfig current = null;
	String currentLayer = null, currentDoc = null, currentEtat = null, currentElement = null;
	boolean inDocument = false, inEtat = false;
	XsString sqlCount = new XsString(SqlConfigMapping.SQL_COUNT), specialCond = new XsString(SqlConfigMapping.SPECIAL_COND);
	boolean inSqlCount = false, inSpecialCond = false; 
	
	String docIdToDerive = "";
	String fileToDerive = "";

	private String baseDirectory;
	
	public PersistenceConfigDeriveParser(Map<String,TPersistenceConfig> cp, String baseDir) throws SAXException, ParserConfigurationException {
		cachedPersistence = cp;
		baseDirectory = baseDir;
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		/**
		 * Element : persistence-derives
		 * on lit extends qui nous donne le fichier de persistence sur lequel on se base
		 */
		if ("persistence-derives".equals(localName)) {
			docIdToDerive = attributes.getValue("extends");
			if (cachedPersistence.get(docIdToDerive)!=null) {
				current = cachedPersistence.get(docIdToDerive).clone();
				current.setBaseDirectory(baseDirectory);
			}
			else current = null;
			fileToDerive = attributes.getValue("file");
			
		// si on n'a pas trouvé la configuration à dériver, on s'arrête là
		} else if (current != null) { 
			
			/**
			 * Le layer
			 */
			if ("layer".equals(localName)) {
				currentLayer = attributes.getValue("name");
			}
			
			/**
			 * le Document que l'on modifie
			 */
			else if ("document".equals(localName)) {
				String oldDocId = attributes.getValue("extends");
				String newDocId = attributes.getValue("id");
				// l'id du doc
				current.getLayer(currentLayer).getDocument(oldDocId).setId(newDocId);
				
				// l'association idDoc / Document
				TDocument tDocTmp = current.getLayer(currentLayer).getDocument(oldDocId);
				current.getLayer(currentLayer).removeDocument(oldDocId);
				current.getLayer(currentLayer).addDocument(newDocId, tDocTmp);
				
				currentDoc = attributes.getValue("id");
				inDocument = true;
			}
			
			/**
			 * Dans un état
			 */
			else if ("etat".equals(localName)) {
				currentEtat = attributes.getValue("id");
				inEtat = true;
				inSqlCount = inSpecialCond = false;
				sqlCount.resetData();
				specialCond.resetData();
				String sTmp = attributes.getValue("import-xslt-file");
				if(sTmp!=null) {
					current.getLayer(currentLayer).getDocument(currentDoc).getEtat(currentEtat).setImportXsltFile(sTmp);
				}
			}
			
			/**
			 * Une table
			 */
			else if ("table".equals(localName)) {
				// Table d'un Etat
				if (inEtat) {
					if ("document".equals(attributes.getValue("type"))) {
						current.getLayer(currentLayer).getDocument(currentDoc).getEtat(currentEtat).getDocumentTable().setBaseName(attributes.getValue("base-name"));
					} else {
						current.getLayer(currentLayer).getDocument(currentDoc).getEtat(currentEtat).getIndexTable(attributes.getValue("extends")).setBaseName(attributes.getValue("base-name"));
						if (attributes.getValue("main")!=null && "true".equals(attributes.getValue("main"))) {
							current.getLayer(currentLayer).getDocument(currentDoc).getEtat(currentEtat).getMaintable().setBaseName(attributes.getValue("base-name"));
						}
					}
				// Table d'un document				
				} else if (inDocument) {
					if ("repository".equals(attributes.getValue("type"))) {
						current.getLayer(currentLayer).getDocument(currentDoc).getRepositoryTable().setBaseName(attributes.getValue("base-name"));
					}
					if ("special-key".equals(attributes.getValue("type"))) {
						current.getLayer(currentLayer).getDocument(currentDoc).getSpecialKeyTable().setBaseName(attributes.getValue("base-name"));
					}
					if ("list-bc".equals(attributes.getValue("type"))) {
						current.getLayer(currentLayer).getDocument(currentDoc).getListBcTable().setBaseName(attributes.getValue("base-name"));
					}
				} 
			}
			
			/**
			 * Un element 
			 */
			if ("element".equals(localName)) {
				currentElement = attributes.getValue("id");
			}
			
			/**
			 * Un sql-count d'un element
			 */
			else if ("sql-count".equals(localName)) {
				inSqlCount = true; 
			}
			/**
			 * Un special-cond d'un element
			 */
			else if ("special-cond".equals(localName)) {
				inSpecialCond = true;
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if ("layer".equals(localName)) {
			currentLayer = "";
		}
		if ("document".equals(localName)) {
			inDocument = false;
			currentDoc = "";
		}
		if ("etat".equals(localName)) {
			inEtat = false;
			currentEtat = "";
		}
		if ("sql-count".equals(localName)) {
			if (current != null)
				current.getLayer(currentLayer).getDocument(currentDoc).getEtat(currentEtat).getElement(currentElement).setSqlCount(sqlCount);
		}
		if ("special-cond".equals(localName)) {
			if (current != null)
				current.getLayer(currentLayer).getDocument(currentDoc).getEtat(currentEtat).getElement(currentElement).setSpecialCond(specialCond);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (inSqlCount) sqlCount.addCharacterData(new String(ch, start, length));
		if (inSpecialCond) specialCond.addCharacterData(new String(ch, start, length));
	}

	public TPersistenceConfig getCurrent() {
		return current;
	}

	public void setCurrent(TPersistenceConfig current) {
		this.current = current;
	}

	public String getFileToDerive() {
		return fileToDerive;
	}

	public void setFileToDerive(String fileToDerive) {
		this.fileToDerive = fileToDerive;
	}

	public String getDocIdToDerive() {
		return docIdToDerive;
	}

	public void setDocIdToDerive(String docIdToDerive) {
		this.docIdToDerive = docIdToDerive;
	}

	public Map<String, TPersistenceConfig> getCachedPersistence() {
		return cachedPersistence;
	}

	public void setCachedPersistence(
			Map<String, TPersistenceConfig> cachedPersistence) {
		this.cachedPersistence = cachedPersistence;
	}
}
