/*
 * 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 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.controls.models;

import fr.gouv.finances.cp.xemelios.common.Constants;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

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.XmlAttributes;
import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
import javax.xml.namespace.QName;



public class ParamModel implements XmlMarshallable {
    private static Logger logger = Logger.getLogger(ParamModel.class);
    public static final transient String TAG = "param";
    public static final transient QName QN = new QName(TAG);
    public String id, name, datatype;
    public SelectModel select;
    public InputModel input;
    private Object value;
    private boolean optional = true;
    
    public ParamModel(QName tagName) {
        super();
    }
    
    public void addCharacterData(String cData) throws SAXException { }
    public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
        if(SelectModel.QN.equals(tagName)) {
            select=(SelectModel)child;
        } else if(InputModel.QN.equals(tagName)) {
            input=(InputModel)child;
        }
    }
    public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
        id=attributes.getValue("id");
        name=attributes.getValue("name");
        datatype=attributes.getValue("datatype");
        if(attributes.getValue("use")!=null) {
            String sTmp = attributes.getValue("use");
            optional = !"required".equals(sTmp);
        }
        value=attributes.getValue("value");
        if(value!=null) checkValueDatatype();
        return this;
    }
    public void validate() throws InvalidXmlDefinition {
        if(select!=null&&input!=null) throw new InvalidXmlDefinition("A param must not own an input and a select");
        if(select==null&&input==null) throw new InvalidXmlDefinition("A param must own either a select or either an input");
    }
    public void marshall(XmlOutputter output) {
        output.startTag(TAG);
        output.addAttribute("id",id);
        output.addAttribute("name",name);
        output.addAttribute("datatype",datatype);
        if(!isOptional()) output.addAttribute("use","required");
        if(value!=null) output.addAttribute("value",value.toString());
        else output.addComment("no value specified");
        if(select!=null) select.marshall(output);
        if(input!=null) input.marshall(output);
        output.endTag(TAG);
    }
    
    public String getId() {return id;}
    public String getName() {return name;}
    public String getDatatype() {return datatype;}
    
    public InputModel getInput() { return input; }
    public SelectModel getSelect() { return select;}
    
    public ParamModel clone() {
        ParamModel pcm = new ParamModel(QN);
        pcm.id = this.id;
        pcm.name = this.name;
        pcm.datatype = this.datatype;
        pcm.select=select.clone();
        pcm.input=input.clone();
        pcm.value=value;
        return pcm;
    }
    public void setValue(Object o) {
//        logger.debug("setting value to "+o);
        if(o==null) this.value=o;
        else {
            String sValue;
            if(o instanceof Pair) sValue = ((Pair)o).key;
            else if(o instanceof Boolean) sValue = ((Boolean)o).toString();
            else sValue = o.toString();
            if("string".equals(datatype)) this.value=sValue;
            else if("integer".equals(datatype)) {
                try {
                    String s = o.toString();
                    if(s.length()>0) {
                        int i = Integer.parseInt(s);
                        this.value=new Integer(i);
                    } else {
                        this.value = new Integer(0);
                    }
                } catch(Throwable t) {
                    logger.debug("parsing int",t);
                }
            } else if("decimal".equals(datatype)) {
                try {
                    String s = o.toString();
                    if(s.length()>0) {
                        BigDecimal bd = new BigDecimal(s);
                        this.value=bd;
                    } else {
                        this.value = new BigDecimal(0.0);
                    }
                } catch(Throwable t) {
                    logger.debug("parsing BigDecimal",t);
                }
            } else if("boolean".equals(datatype)) {
                boolean b = Boolean.valueOf(o.toString());
                this.value = new Boolean(b);
            } else if("date".equals(datatype)) {
                SimpleDateFormat sdf = new SimpleDateFormat(System.getProperty(Constants.SYS_PROP_DATE_FORMAT));
                try {
                    Date d = sdf.parse(o.toString());
                    this.value = d;
                } catch(Throwable t) {
                    logger.debug("parsing date",t);
                }
            }
//            logger.debug("value set to "+this.value);
        }
    }
    public Object getValue() { return value; }
    public boolean isOptional() { return optional; }
    private void checkValueDatatype() {
    	setValue(value);
    }

    public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
        QName tagName = new QName(uri,localName);
        if(SelectModel.QN.equals(tagName)) {
            return select;
        } else if(InputModel.QN.equals(tagName)) {
            return input;
        }
        return null;
    }

    public QName getQName() {
        return QN;
    }
}
