/*
 * 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.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.Vector;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import fr.gouv.finances.cp.utils.Pair;
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 selection
 * @author chm
 */
public class SelectModel implements NoeudModifiable {
    private static Logger logger = Logger.getLogger(SelectModel.class);
    private NoeudModifiable _NMParent = null;
    private String configXPath = null;
    
    public static final transient String TAG = "select";
    public static final int SORT_NO=0;
    public static final int SORT_KEY=1;
    public static final int SORT_LIB=2;
    
    private Vector<OptionModel> options;
    private HashMap<String,OptionModel> hOptions;
    private String id, libelle, value;
    private Vector<RecherchePaireModel> recherches;	// des recherches dans la nomenclature
    private HashMap<String,RecherchePaireModel> hRecherches;
    private Vector<SpecialKeyEntryModel> specialKeys;	// des recherches dans les cles-speciales
    private HashMap<String,SpecialKeyEntryModel> hSpecialKeys;
    private String sort = "no";
    public SelectModel(String tagName) {
        super();
        options = new Vector<OptionModel>();
        hOptions = new HashMap<String,OptionModel>();
        recherches = new Vector<RecherchePaireModel>();
        hRecherches = new HashMap<String,RecherchePaireModel>();
        specialKeys = new Vector<SpecialKeyEntryModel>();
        hSpecialKeys = new HashMap<String,SpecialKeyEntryModel>();
    }
    public void addCharacterData(String cData) throws SAXException {}
    public void addChild(XmlMarshallable child, String tagName) throws SAXException {
        if(OptionModel.TAG.equals(tagName)) {
            OptionModel om = (OptionModel)child;
            om.setParentAsNoeudModifiable(this);
            options.add(om);
            hOptions.put(om.getValue(), om);
        } else if("recherche-paire".equals(tagName)) {
            RecherchePaireModel rpm = (RecherchePaireModel)child;
            rpm.setParentAsNoeudModifiable(this);
            recherches.add(rpm);
//	    	hRecherches.put(rpm.getPath().getPath(), rpm);
            hRecherches.put(rpm.getId(), rpm);
        } else if(SpecialKeyEntryModel.TAG.equals(tagName)) {
            SpecialKeyEntryModel skem = (SpecialKeyEntryModel)child;
            skem.setParentAsNoeudModifiable(this);
            specialKeys.add(skem);
            hSpecialKeys.put(String.valueOf(skem.getPos()), skem);
        }
    }
    public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
        id=(attributes.getValue("id")!=null?attributes.getValue("id"):id);
        libelle=(attributes.getValue("libelle")!=null?attributes.getValue("libelle"):libelle);
        value=(attributes.getValue("value")!=null?attributes.getValue("value"):value);
        sort=(attributes.getValue("sort")!=null?attributes.getValue("sort"):sort);
        return this;
    }
    public void marshall(XmlOutputter output) {
        output.startTag(TAG);
        output.addAttribute("id",id);
        output.addAttribute("sort",sort);
        if(libelle!=null) output.addAttribute("libelle",StringEscapeUtils.escapeXml(libelle));
        for(OptionModel om:options) om.marshall(output);
        for(RecherchePaireModel rpm:recherches) rpm.marshall(output);
        output.endTag(TAG);
    }
    public void validate() throws InvalidXmlDefinition {
        if(id==null || id.length()==0) throw new InvalidXmlDefinition("//"+TAG+"/@id is required");
        for(OptionModel om:options) om.validate();
        for(RecherchePaireModel rpm:recherches) rpm.validate();
        for(SpecialKeyEntryModel spe:specialKeys) spe.validate();
    }
    public String getId() {return id;}
    public String getLibelle() {return libelle;}
    public Vector<OptionModel> getOptions() {return options;}
    public Vector<RecherchePaireModel> getRecherches() {
        return recherches;
    }
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }
    @Override
    public SelectModel clone() {
        SelectModel sm = new SelectModel(TAG);
        sm.id=this.id;
        sm.libelle=this.libelle;
        sm.value=value;
        sm.sort=sort;
        for(OptionModel om:this.options) try {sm.addChild(om.clone(), om.TAG);} catch (Throwable t) {}
        for(RecherchePaireModel rpm:this.recherches) try {sm.addChild(rpm.clone(), "recherche-paire");} catch (Throwable t) {}
        for(SpecialKeyEntryModel skem:this.specialKeys) try {sm.addChild(skem.clone(), skem.TAG);} catch (Throwable t) {}
        return sm;
    }
    public int getSortBy() {
        if("no".equals(sort)) return SORT_NO;
        else if("key".equals(sort)) return SORT_KEY;
        else return SORT_LIB;
    }
    public Vector<SpecialKeyEntryModel> getSpecialKeys() {
        return specialKeys;
    }
    @SuppressWarnings("unchecked")
    public Collection<Pair> getNewRecipient() {
        int sortBy = getSortBy();
        if(sortBy==SORT_NO) return new Vector<Pair>();
        Comparator<Pair> cp;
        if(sortBy==SORT_KEY) {
            cp = new Comparator() {
                public int compare(Object o1, Object o2) {
                    Pair p1=(Pair)o1;
                    Pair p2=(Pair)o2;
                    return p1.key.compareTo(p2.key);
                }
            };
        } else {
            cp = new Comparator() {
                public int compare(Object o1, Object o2) {
                    Pair p1=(Pair)o1;
                    Pair p2=(Pair)o2;
                    return p1.libelle.compareTo(p2.libelle);
                }
            };
        }
        return new TreeSet<Pair>(cp);
    }
    
    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 void setParentAsNoeudModifiable(NoeudModifiable p) {
        this._NMParent = p;
    }
    public NoeudModifiable getParentAsNoeudModifiable() {
        return this._NMParent;
    }
    public NoeudModifiable getChildAsNoeudModifiable(String tagName, String id) {
        if(OptionModel.TAG.equals(tagName)) {
            return hOptions.get(id);
        } else if("recherche-paire".equals(tagName)) {
            return hRecherches.get(id);
        } else if(SpecialKeyEntryModel.TAG.equals(tagName)) {
            return hSpecialKeys.get(id);
        } else {
            return null;
        }
    }
    public String[] getChildIdAttrName(String childTagName) {
        if(OptionModel.TAG.equals(childTagName)) {
            return new String[]{"value"};
        } else if("recherche-paire".equals(childTagName)) {
            //return new String[]{"path"};
            return new String[]{"id"};
        } else if(SpecialKeyEntryModel.TAG.equals(childTagName)) {
            return new String[]{"pos"};
        } else {
            return null;
        }
    }
    public void resetCharData() {
    }
    public String getIdValue() { return getId(); }
    public String getConfigXPath() {
        if(configXPath==null) {
            if(getParentAsNoeudModifiable()!=null) configXPath = getParentAsNoeudModifiable().getConfigXPath();
            else configXPath="";
            configXPath+="/"+TAG+"[@id='"+getId()+"']";
        }
        return configXPath;
    }

}
