/*
 * Copyright
 *   2007 axYus - www.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.chorus;

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;

/**
 * - présence de divers items CHORUS
 * @author laurent.meckert
 */
public abstract class CHORUS00 extends AbstractUnitControl {

	protected StringBuilder charsBuffer = new StringBuilder();
	private Vector<Anomalie> anos = new Vector<Anomalie>();
	private Hashtable<String, Object> hParams;
	private boolean isExecutable = false;
	/**
	 * La balise du document général
	 */
	private String docId = null;
	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 om_IdLine;
	private String om_AipName;
	/**
	 * Chemins vers les divers éléments que l'on veut lire.
	 */
	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/";
	private static final String CHEMIN_INVOICE_LINE = "EtatsFrais/Invoice/InvoiceLine/";
	private static final String CHEMIN_INVOICE_IDLINE = "EtatsFrais/Invoice/InvoiceLine/ID/";
	private static final String CHEMIN_INVOICE_AIP_NAME = "EtatsFrais/Invoice/InvoiceLine/Item/AdditionalItemProperty/Name/";
	private static final String CHEMIN_INVOICE_AIP_VALUE = "EtatsFrais/Invoice/InvoiceLine/Item/AdditionalItemProperty/Value/";
	private static final String CHAMP_CHORUS = "CHAMP_CHORUS";
	/**
	 * La chaine cible
	 */
	private static final String FIN_INVOICE_LINE = "EtatsFrais/Invoice/InvoiceLine/";
	private static final String ON_RETURN_ANOMALIES = FIN_INVOICE_LINE;
	private Hashtable<String, String> hashPresents = new Hashtable<String, String>();
	/**
	 * 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_IDINVOICELINE = "#CBC_IDINVOICELINE#";

	// Le champ chorus a rechercher
	abstract protected String nomAChercher();

	abstract protected Logger getLogger();

	abstract protected String getCtrlId();

	public void startDocument() throws SAXException {
		if (isExecutable) {
			getLogger().info("In " + getCtrlId());
		} else {
			getLogger().info(getCtrlId() + " not executed");
		}

	}

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

	public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) {
		if (!isExecutable) {
			return;
		}
		if (xpath.endsWith(CHEMIN_INVOICE_LINE)) {
			anos = new Vector<Anomalie>();
		}
		if (xpath.endsWith(CHEMIN_INVOICE_AIP_VALUE)) {
			if (om_AipName.equals(nomAChercher())) {
				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 {
		if (!isExecutable) {
			return null;
		}
		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(CHEMIN_INVOICE_IDLINE)) {
			om_IdLine = value;
		}
		if (xpath.endsWith(CHEMIN_INVOICE_AIP_NAME)) {
			om_AipName = value;
		}
		if (xpath.endsWith(CHEMIN_INVOICE_AIP_VALUE)) {
			if (om_AipName.equals(nomAChercher())) {
				hashPresents.put(CHAMP_CHORUS, value);
			}
		}
		if (xpath.endsWith(ON_RETURN_ANOMALIES)) {
			if (hashPresents.get(CHAMP_CHORUS) == null || hashPresents.get(CHAMP_CHORUS).equals("")) {

				String msg = getDocumentModel().getControlById(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_IDINVOICELINE, om_IdLine);
				//String path = "@added:primary-key='"  + om_IdOm + "-" + om_IdLine + "'";
				String path = "cbc:ID/text()='" + om_IdOm + "'";
				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);
				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);
			}

			hashPresents.clear();
			nodesId.clear();
			return anos;
		} else {
			return null;
		}

	}

	public void endDocument() throws SAXException {
	}

	public void characters(char[] ch, int start, int length, String xpath) {
		if (!isExecutable) {
			return;
		}
		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;
		Object secteur = hParams.get("secteur");
		if (secteur == null
				  || !(secteur.toString().equals("Etat"))) {
			// les controles Chorus pas executes si secteur local
			isExecutable = false;
		} else {
			isExecutable = true;
		}
	}

	public void setDocumentLocator(Locator locator) {
	}
}
