/*
 * 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.common.config;

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

import org.apache.log4j.Logger;
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.NoeudModifiable;
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;

/**
 * Modelise une liste de resultats
 * @author chm
 */
public class ListeResultatModel implements NoeudModifiable, Cloneable {
    private static Logger logger = Logger.getLogger(ListeResultatModel.class);
    private ElementModel parent;
    private NoeudModifiable _NMParent = null;
    public static final transient String TAG = "liste-resultat";
    
    private String triDefaut, ordre;
    private Hashtable<String,ChampModel> champs;
    private Vector<ChampModel> listeChamps;
    private HashMap<String,ChampModel> hChampModels;
    private Vector<HiddenModel> hiddens;
    private HashMap<String,HiddenModel> hHiddenModels;
    private Vector<WidgetModel> widgets;
    private HashMap<String,WidgetModel> hWidgets;
    
    public ListeResultatModel(String tagName) {
        super();
        champs = new Hashtable<String,ChampModel>();
        listeChamps = new Vector<ChampModel>();
        hChampModels = new HashMap<String,ChampModel> ();
        hiddens = new Vector<HiddenModel>();
        hHiddenModels = new HashMap<String,HiddenModel> ();
        widgets = new Vector<WidgetModel>();
        hWidgets = new HashMap<String,WidgetModel>();
    }
    public void addCharacterData(String cData) throws SAXException {}
    public void addChild(XmlMarshallable child, String tagName) throws SAXException {
        if(ChampModel.TAG.equals(tagName)) {
            ChampModel cm = (ChampModel)child;
            cm.setParent(this);
            cm.setParentAsNoeudModifiable(this);
            champs.put(cm.getId(),cm);
            listeChamps.add(cm);
            hChampModels.put(cm.getId(), cm);
        } else if(HiddenModel.TAG.equals(tagName)) {
            HiddenModel hm = (HiddenModel)child;
            hm.setParentAsNoeudModifiable(this);
            hiddens.add(hm);
            hHiddenModels.put(hm.getName(), hm);
        } else if(WidgetModel.TAG.equals(tagName)) {
            WidgetModel wm = (WidgetModel)child;
            wm.setParentAsNoeudModifiable(this);
            widgets.add(wm);
            hWidgets.put(wm.getId(),wm);
        }
    }
    public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
        triDefaut=(attributes.getValue("tri-defaut")!=null?attributes.getValue("tri-defaut"):triDefaut);
        ordre=(attributes.getValue("ordre")!=null?attributes.getValue("ordre"):ordre);
        return this;
    }
    public void marshall(XmlOutputter output) {throw new Error("Not yet implemented"); }
    public void validate() throws InvalidXmlDefinition {
        if(triDefaut==null) throw new InvalidXmlDefinition("//"+TAG+"/@tri-defaut is required ("+getConfigXPath()+")");
        for(String s:triDefaut.split(",")) {
            if(s.length()==0) continue;
            if(champs.get(s)==null) throw new InvalidXmlDefinition(getConfigXPath()+"/@tri-defaut references a champ that is not defined: "+s);
        }
        if(ordre==null) throw new InvalidXmlDefinition("//"+TAG+"/@ordre is required ("+getConfigXPath()+")");
        for(WidgetModel wm:widgets) wm.validate();
        for(ChampModel cm:listeChamps) cm.validate();
        for(HiddenModel h:hiddens) h.validate();
    }
    public Hashtable<String, ChampModel> getChamps() {return champs;}
    public String getOrdre() {return ordre;}
    public String getTriDefaut() {return triDefaut;}
    public Vector<ChampModel> getListeChamps() { return listeChamps; }
    @Override
    public ListeResultatModel clone() {
        ListeResultatModel other = new ListeResultatModel(TAG);
        other.triDefaut = (triDefaut==null?null:new String(triDefaut));
        other.ordre = (ordre==null?null:new String(ordre));
        for(ChampModel cm:listeChamps) {
            ChampModel cm2 = cm.clone();
            try { other.addChild(cm2,ChampModel.TAG); } catch(SAXException ignore) {}
        }
        other.champs.putAll(this.champs);
        for(HiddenModel hm:hiddens) {
            try { other.addChild(hm.clone(),HiddenModel.TAG); } catch(SAXException saxEx) {}
        }
        for(WidgetModel wm:widgets) {
            try { other.addChild(wm.clone(),WidgetModel.TAG); } catch(SAXException saxEx) {}
        }
        return other;
    }
    public ElementModel getParent() { return parent; }
    public void setParent(ElementModel parent) { this.parent=parent; }
    public void setOrdre(String ordre) { this.ordre = ordre; }
    public void setTriDefaut(String triDefaut) { this.triDefaut = triDefaut; }
    
    public Vector<HiddenModel> getHiddens() { return hiddens; }
    
    
    public void setParentAsNoeudModifiable(NoeudModifiable p) {
        this._NMParent = p;
    }
    public NoeudModifiable getParentAsNoeudModifiable() {
        return this._NMParent;
    }
    public NoeudModifiable getChildAsNoeudModifiable(String tagName, String id) {
        if(ChampModel.TAG.equals(tagName)) {
            return hChampModels.get(id);
        } else if(HiddenModel.TAG.equals(tagName)) {
            return hHiddenModels.get(id);
        } else if(WidgetModel.TAG.equals(tagName)) {
            return hWidgets.get(id);
        } else {
            return null;
        }
    }
    public void modifyAttr(String attrName, String value) {
        // TODO Raccord de m�thode auto-g�n�r�
        
    }
    public void modifyAttrs(Attributes attrs) {
        try {
            getAttributes(new XmlAttributes(attrs));
        } catch (Exception e) {
            logger.error("Erreur lors de la mise � jour des attributs : "+e);
        }
    }
    public String[] getChildIdAttrName(String childTagName) {
        if(ChampModel.TAG.equals(childTagName)) {
            return new String[]{"id"};
        } else if(HiddenModel.TAG.equals(childTagName)) {
            return new String[]{"name"};
        } else if(WidgetModel.TAG.equals(childTagName)) {
            return new String[]{"id"};
        } else {
            return null;
        }
    }
    public void resetCharData() {
    }
    public String getIdValue() { return null; }
    
    public void removeAllChamps() {
        this.champs = new Hashtable<String,ChampModel>();
        this.listeChamps = new Vector<ChampModel>();
        this.hChampModels = new HashMap<String,ChampModel>();
    }
    public Vector<WidgetModel> getWidgets() { return widgets; }
    private String configXPath = null;
    public String getConfigXPath() {
        if(configXPath==null) {
            if(getParentAsNoeudModifiable()!=null) configXPath = getParentAsNoeudModifiable().getConfigXPath();
            else configXPath="";
            configXPath+="/"+TAG;
        }
        return configXPath;
    }
}
