/*
 * Copyright 
 *   2007 axYus - www.axyus.com
 *   2007 JP.Tessier - jean-philippe.tessier@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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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.controls.models;

import java.util.Hashtable;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
import fr.gouv.finances.dgfip.xemelios.common.config.CollectiviteInfosModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsMapping;
import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
import fr.gouv.finances.dgfip.xemelios.common.config.NamespaceModel;
import fr.gouv.finances.dgfip.xemelios.common.config.RecherchePaireModel;
import javax.xml.namespace.QName;

public class DocumentControlModel implements XmlMarshallable {
    
    public static final transient String TAG = "document";
    public static final transient QName QN = new QName(TAG);
    private String id;
    private Vector<ParamModel> params;
    private Vector<ControlModelTech> controlsTech;
    private Vector<ControlModel> controls;
    private Hashtable<String,ControlModel> indexedControls;
    private Hashtable<String,ControlModelTech> indexedControlsTech;
    private CollectiviteInfosModel collectivitePath;
    private RecherchePaireModel budgetPath;
    private DocumentModel parentDocumentModel;
    private EngineModel engine;
    
    public DocumentControlModel(QName tagName) {
        super();
        params=new Vector<ParamModel>();
        controls=new Vector<ControlModel>();
        controlsTech=new Vector<ControlModelTech>();
        indexedControls = new Hashtable<String,ControlModel>();
        indexedControlsTech = new Hashtable<String,ControlModelTech>();
    }
    
    public void addCharacterData(String cData) throws SAXException { }
    public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
        if(ParamModel.QN.equals(tagName)) {
            params.add((ParamModel)child);
        } else if(ControlModel.QN.equals(tagName)) {
            ControlModel cm = (ControlModel)child;
            if(indexedControls.containsKey(cm.getId())) {
                ControlModel old = indexedControls.get(cm.getId());
                controls.remove(old);
                indexedControls.remove(old.getId());
            }
            controls.add(cm);
            indexedControls.put(cm.getId(),cm);
        } else if(ControlModelTech.QN.equals(tagName)) {
            ControlModelTech cm = (ControlModelTech)child;
            if(indexedControlsTech.contains(cm.getId())) {
                ControlModelTech old = indexedControlsTech.get(cm.getId());
                controlsTech.remove(old);
                indexedControlsTech.remove(old.getId());
            }
            controlsTech.add(cm);
            indexedControlsTech.put(cm.getId(),cm);
        } else if(CollectiviteInfosModel.QN.equals(tagName)) {
            collectivitePath = (CollectiviteInfosModel)child;
        } else if (DocumentsMapping.BUDGET_PATH.equals(tagName)) {
            budgetPath = (RecherchePaireModel) child;
        } else if(EngineModel.QN.equals(tagName)) {
            engine = (EngineModel)child;
        }
    }
    public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
        id=attributes.getValue("id");
        return this;
    }
    public void validate() throws InvalidXmlDefinition {
        for(ParamModel pcm:params) pcm.validate();
        for(ControlModel cm:controls) cm.validate();
        for(ControlModelTech cm:controlsTech) cm.validate();
    }
    public void marshall(XmlOutputter output) {
        output.startTag (TAG);
        output.addAttribute("id",id);
        if(collectivitePath!=null) collectivitePath.marshall(output);
        if(budgetPath!=null) budgetPath.marshall(output);
        for(ParamModel pm:params) pm.marshall(output);
        if(engine!=null) engine.marshall(output);
        for(ControlModelTech cm:controlsTech) cm.marshall(output);
        for(ControlModel cm:controls) cm.marshall(output);
        output.endTag(TAG);
    }
    
    public String getDocumentId() {return id;}
    
    public ParamModel getParamById(String etatId) {
        for(ParamModel param:params) {
            if(param.getId().equals(etatId)) return param;
        }
        return null;
    }
    
    public ControlModel getControlById(String ctrlId) {
        return indexedControls.get(ctrlId);
    }
    
    public ControlModelTech getControlTechById(String ctrlId) {
        return indexedControlsTech.get(ctrlId);
    }
    
    public Vector<ControlModelTech> getControlsTech(){
        return controlsTech;
    }
        
    public Vector<ControlModel> getControls(){
        return controls;
    }
    public Vector<ParamModel> getParams(){
        return params;
    }
    
    @Override
    public DocumentControlModel clone() {
        DocumentControlModel dcm = new DocumentControlModel(QN);
        dcm.id = this.id;
        if(collectivitePath!=null)
            dcm.collectivitePath = collectivitePath.clone();
        if(budgetPath!=null)
            dcm.budgetPath=budgetPath.clone();
        if(engine!=null)
            dcm.engine = engine.clone();
        for(ControlModel cm:getControls()){
        	try{
        		addChild(cm.clone(),ControlModel.QN);
        	} catch(SAXException ignore){}
        }
        for(ControlModelTech cmt:getControlsTech()) {
        	try {
        		addChild(cmt.clone(), ControlModelTech.QN);
        	} catch(SAXException ignore) {}
        }
        for(ParamModel pm:getParams()) {
        	try {
        		addChild(pm.clone(), ParamModel.QN);
        	} catch(SAXException ignore) {}
        }
        return dcm;
    }

    public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
        QName tagName = new QName(uri,localName);
        if(ControlModel.QN.equals(tagName)) {
            return indexedControls.get(atts.getValue("id"));
        } else if(ControlModelTech.QN.equals(tagName)) {
            return indexedControlsTech.get(atts.getValue("id"));
        }
        return null;
   }

    public QName getQName() {
        return QN;
    }
    public CollectiviteInfosModel getCollectivitePath() {
        if(collectivitePath==null) {
            return getParentDocumentModel().getCollectivitePath();
        } else {
            return collectivitePath;
        }
    }
    protected DocumentModel getParentDocumentModel() {
        if(parentDocumentModel==null) {
            try {
                parentDocumentModel = Loader.getDocumentsInfos(null).getDocumentById(id);
            } catch(Exception ex) {}
        }
        return parentDocumentModel;
    }
	  public NamespaceModel getNamespaces() {
        return getParentDocumentModel().getNamespaces();
    }

    public RecherchePaireModel getBudgetPath() {
        if(budgetPath==null) {
            return getParentDocumentModel().getBudgetPath();
        } else {
            return budgetPath;
        }
    }
    public EngineModel getEngine() { return engine; }
    public void setEngine(EngineModel engine) { this.engine=engine; }
}