/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 L.Meckert laurent.meckert@axyus.com
 *   2009 L.Meckert laurent.meckert@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.dgfip.xemelios.controls.etatFrais.values;

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

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import fr.gouv.finances.cp.xemelios.controls.AbstractUnitControl;
import fr.gouv.finances.cp.xemelios.controls.Anomalie;
import fr.gouv.finances.cp.xemelios.controls.IdGenerator;
import fr.gouv.finances.cp.xemelios.controls.Node;

/**
 * code générique pour les champs n'acceptant qu'une liste
 * de valeurs possibles
 * @author laurent.meckert
 */
public abstract class VALUES00 extends AbstractUnitControl {

	private final static Logger logger = Logger.getLogger(VALUES00.class);

	/**
	 * @return the valuesString
	 */
	abstract public String getValuesString();

	/**
	 * @param aValuesString the valuesString to set
	 */
	abstract public void setValuesString(String aValuesString);

	/**
	 * @return the valuesList
	 */
	abstract public String[] getValuesList();

	/**
	 * @param aValuesList the valuesList to set
	 */
	abstract public void setValuesList(String[] aValuesList);
	private Vector<Anomalie> anos = new Vector<Anomalie>();
	private Hashtable<String, Object> hParams;
	protected StringBuilder charsBuffer = new StringBuilder();
	/**
	 * La balise du document général
	 */
	private String docId = null;
	private String nodeId = null;
	private static final String CHEMIN_INVOICE = "EtatsFrais/Invoice/";
	private static final String CHEMIN_INVOICEDATE = "EtatsFrais/Invoice/IssueDate/";
	private static final String CHEMIN_INVOICE_IDINVOICE = "EtatsFrais/Invoice/ID/";
	private static final String CHEMIN_INVOICE_TYPINVOICE = "EtatsFrais/Invoice/InvoiceTypeCode/";
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */
	private ArrayList<Node> nodesId = new ArrayList<Node>();
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */
	private String om_IssueDate;
	private String om_IdOm;
	private String om_TypEtatFrais;
	private String ID_Invoice_Unique = "";
	/**
	 * Variables devant être remplacées dans le message
	 */
	private static final String MSG_CBC_ID = "#CBC_ID#";
	private static final String MSG_CBC_ISSUEDATE = "#CBC_ISSUEDATE#";
	private static final String MSG_CBC_INVOICETYPECODE = "#CBC_INVOICETYPECODE#";
	private static final String MSG_CBC_ELEMENT = "#CBC_ELEMENT#";
	private static final String MSG_CBC_VALUE = "#CBC_VALUE#";
	private static final String MSG_CBC_LISTVALUES = "#CBC_LISTVALUES#";

	abstract protected String getXpath();

	abstract protected String getReturnAnomalies();

	abstract protected Logger getLogger();

	abstract protected String getCtrlId();

	abstract protected String getValuesParameterName();
	private boolean found = false;

	public void startDocument() throws SAXException {
		getLogger().info("In " + getCtrlId());
	}

	public void setDocId(String docID) {
		this.docId = docID;
	}

	public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) {
		if (xpath.endsWith(CHEMIN_INVOICE)) { 
			ID_Invoice_Unique = atts.getValue("ano:unique-id");
		}
		if (xpath.endsWith(getXpath())) {
			nodesId.clear();
			anos = new Vector<Anomalie>();
			nodesId.add(new Node(atts.getValue("ano:node-id")));
			found = false;
		}
		/*if (xpath.endsWith(getReturnAnomalies())) {
			nodesId.add(new Node(atts.getValue("ano:node-id")));
		}*/
		this.charsBuffer.delete(0, this.charsBuffer.length());
	}

	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		String value = this.charsBuffer.toString();
		if (xpath.endsWith(CHEMIN_INVOICEDATE)) {
			om_IssueDate = value;
		}
		if (xpath.endsWith(CHEMIN_INVOICE_IDINVOICE)) {
			om_IdOm = value;
		}
		if (xpath.endsWith(CHEMIN_INVOICE_TYPINVOICE)) {
			om_TypEtatFrais = value;
		}

		if (xpath.endsWith(getXpath())) {
			// comparer avec les valeurs possible dans valuesList
			for (String s : getValuesList()) {
				if (s.equals(value)) {
					found = true;
					break;
				}
			}
			if (!found) {
				setBadValue(value);
			}
		}
		if (xpath.endsWith(getReturnAnomalies())) {
			if (getBadValue() != null) {
				String msg = getDocumentModel().getControlById(this.getCtrlId()).getMessage().getHtmlContent();
				msg = msg.replaceAll(MSG_CBC_ID, om_IdOm);
				msg = msg.replaceAll(MSG_CBC_ISSUEDATE, om_IssueDate);
				msg = msg.replaceAll(MSG_CBC_INVOICETYPECODE, om_TypEtatFrais);
				msg = msg.replaceAll(MSG_CBC_ELEMENT, getXpath());
				msg = msg.replaceAll(MSG_CBC_VALUE,getBadValue());
				msg = msg.replaceAll(MSG_CBC_LISTVALUES, getValuesString());
				setBadValue(null);
				String path = "@ano:unique-id='" + ID_Invoice_Unique + "'";
				String anoId = IdGenerator.nextId();
				String libelleLien = "Invoice " + om_IdOm;
				Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
				//xslParams.put("elementId", "");
				//xslParams.put("browser-destination", "internal");
				xslParams.put("anoId", anoId);
				xslParams.put("presentation","src");
				Anomalie ano = new Anomalie(anoId,
						  getDocumentModel().getControlById(getCtrlId()).getId(),
						  getDocumentModel().getControlById(getCtrlId()).getLibelle(),
						  getDocumentModel().getDocumentId(),
						  "EtatFrais", //  xpath.split("/")[0],
						  "invoice", // élément importable
						  om_IdOm, // id élément importable
						  localName,
						  libelleLien,
						  msg,
						  getDocumentModel().getControlById(getCtrlId()).getRegle().getHtmlContent(),
						  getDocumentModel().getControlById(getCtrlId()).getSeverity(),
						  path, // xpath vers l'invoice line  sous lequel se trouve l'anomalie
						  xslParams); // paramètres supplémentaires pour accéder à l'élément en anomalie
				ano.addAll(nodesId);
				anos.add(ano);
				return anos;
			} else {

				return null;
			}
		}

		return null;

	}

	public void endDocument() throws SAXException {
	}

	public void characters(char[] ch, int start, int length, String xpath) {
		this.charsBuffer.append(ch, start, length);
	}

	public void ignorableWhitespace(char[] ch, int start, int length, String xpath) {
	}

	public void startPrefixMapping(String prefix, String uri, String xpath) {
	}

	public void endPrefixMapping(String prefix, String xpath) {
	}

	public void processingInstruction(String target, String data, String xpath) {
	}

	public void skippedEntity(String name, String xpath) {
	}

	public void setParameters(Hashtable<String, Object> params) {
		this.hParams = params;
		if (hParams.get(getValuesParameterName()) != null) {
			setValuesString(hParams.get(getValuesParameterName()).toString());
			setValuesList(getValuesString().split("[ ,]+"));
		}
	}

	public void setDocumentLocator(Locator locator) {
	}

	/**
	 * @return the badValue
	 */
	abstract public String getBadValue();

	/**
	 * @param badValue the badValue to set
	 */
	abstract public void setBadValue(String badValue);
}
