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

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 valideur d'ordre de mission
 * @author laurent.meckert
 */
public class PRES01 extends AbstractUnitControl { //implements ConstantsControlsPESv2 {

	protected StringBuilder charsBuffer = new StringBuilder();
	private final static Logger logger = Logger.getLogger(PRES01.class);
	public static final transient String CTRL_ID = "PRES01";
	private Vector<Anomalie> anos = new Vector<Anomalie>();
	private Hashtable<String, Object> hParams;
	  protected  Logger getLogger() {
      return logger;
   }
  protected  String getCtrlId() {
      return CTRL_ID;
   }
	/**
	 * 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 ID_Invoice_Unique = "";
	/**
	 * Chemins vers les divers éléments que l'on veut lire.
	 */

	// la balise valideur de l'ordre de mission
	//private static final String CHEMIN_VALIDEUR_OM = "EtatsFrais/Invoice/UBLExtensions/UBLExtension/ExtensionContent/EtatFraisExtension/OrdreMission/Valideur/PartyIdentification";
	private static final String CHEMIN_VALIDEUR_OM = "OrdreMission/Valideur/PartyIdentification/ID/";
	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/";
	/**
	 * La chaine cible
	 */
	private static final String FIN_INVOICE = "EtatsFrais/Invoice/";
	private static final String ON_RETURN_ANOMALIES = FIN_INVOICE;
	private Hashtable<String, String> hashPresents = new Hashtable<String, String>();
	private static final String VALIDEUR = "Valideur";

	/**
	 * 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#";

	public void startDocument() throws SAXException {
		logger.info("In " + CTRL_ID);
	}

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

	public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) {
		// 1   
		if (xpath.endsWith(CHEMIN_INVOICE)) {
			anos = new Vector<Anomalie>(); 
            ID_Invoice_Unique = atts.getValue("ano:unique-id");
		}
		if (xpath.endsWith(CHEMIN_VALIDEUR_OM)) {
			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(CHEMIN_VALIDEUR_OM)) {
			hashPresents.put(VALIDEUR, value);
		}
		if (xpath.endsWith(ON_RETURN_ANOMALIES)) {
			if (hashPresents.get(VALIDEUR) == null || hashPresents.get(VALIDEUR).equals("")) {

				String msg = getDocumentModel().getControlById(CTRL_ID).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);

				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);
			}

			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) {
		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;
	}

	public void setDocumentLocator(Locator locator) {
	}
}
