/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2010 C ARIOUAT - assia.ariouat@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.facturessansengagementtiers;
import java.util.Hashtable;
import java.util.Stack;
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;

/*"Implémente le contrôle N° M155 
 * PYMT_METH prend les valeurs suivantes  : ‘1’, ‘9’, ‘F’, ‘ ’ (Vide)
 * * @author Assia ARIOUAT
 */

public class M156 extends AbstractUnitControl {
	
	private final static Logger logger = Logger.getLogger(M156.class);
    public static final transient String CTRL_ID = "CTL-M156";
	private Hashtable<String,Object> hParams;
	Vector<Anomalie> anomalies = new Vector<Anomalie>();
	
	/**
	 * Variables devant être remplacées dans le message
	 */
	private static final String MSG_IDPOSTE = "#ID_POSTE#";
	private static final String MSG_ENTETE_IDFACTURE = "#ENTETE_IDFACTURE#";
	private static final String MSG_POSTE_PYMT_METH = "#ENTETE_PYMT_METH#";
	private static final String MSG_ERREUR = "#ERREUR#";
	
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */

	private String pymt_meth = "";
	private String pymtmeth_NodeId = "";
	private String entete_numfact = "";
	private String ID_FACTURE_Unique = "";
	private String generatedId = "";
	private Stack<StringBuffer> chars = new Stack<StringBuffer>();
	private String numLigneTexte = "";
	private String idposte = "";
		
	/**
	 * Chemins vers les divers éléments que l'on veux lire
	 */
	private static final String CHEMIN_FACTURE ="/FACTURE/";
	private static final String CHEMIN_ENTETE_NUM_FACT= "/ENTETE/NUM_FACT/";
	private static final String CHEMIN_ENTETE= "/ENTETE/";
	private static final String CHEMIN_PYMT_METH= "/FACTURE/LIGNE_POSTE/PYMT_METH/";
	private static final String CHEMIN_POSTE = "/FACTURE/LIGNE_POSTE/";
	private static final String CHEMIN_POSTEID = "/FACTURE/LIGNE_POSTE/POSTE/";
	private static final String RETURN_ANOMALIES_PATH = "/FACTURE/";
			
	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
		
	}	

public void startElement(String uri, String localName, String qName,Attributes atts, String xpath) {
		
		if (xpath.endsWith(CHEMIN_FACTURE)){
			anomalies.clear();
			generatedId = atts.getValue("added:generated-id");
			ID_FACTURE_Unique = atts.getValue("ano:unique-id");
		}
		if (xpath.endsWith(CHEMIN_ENTETE)){
			 entete_numfact="" ;
		}
		if (xpath.endsWith(CHEMIN_POSTE)){
			pymt_meth = pymtmeth_NodeId = "";
		}
					
		if(atts.getValue("txt2xml:LineTxt")!=null){
		numLigneTexte = atts.getValue("txt2xml:LineTxt");
			} else {
				numLigneTexte = "";
			}
		
		if (xpath.endsWith(CHEMIN_PYMT_METH)){
			pymtmeth_NodeId = atts.getValue("ano:node-id");
		}
		// A chaque nouvel élément, on vide la Stack
		chars.push(new StringBuffer());
	}


public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {

	String erreur = "";
	if (xpath.endsWith(CHEMIN_POSTEID)) {
		idposte = chars.peek().toString();
	}
	if (xpath.endsWith(CHEMIN_ENTETE_NUM_FACT)) {
		entete_numfact = chars.peek().toString();
	}
	if (xpath.endsWith(CHEMIN_PYMT_METH)) {
		pymt_meth = chars.peek().toString();
	}
	
	if (xpath.endsWith(CHEMIN_POSTE)){
				
		if (!pymt_meth.equals("1") && !pymt_meth.equals("9")&& !pymt_meth.equals("F")&& !pymt_meth.equals("")&& !pymt_meth.equals(" ")){

			String msg = (numLigneTexte.length()>0?"Ligne n°"+numLigneTexte+" : ":"");
			msg += getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
			msg = msg.replaceAll(MSG_ENTETE_IDFACTURE, entete_numfact);
			msg = msg.replaceAll(MSG_POSTE_PYMT_METH, pymt_meth);
			msg = msg.replaceAll(MSG_IDPOSTE, idposte);
						
			String path = "@ano:unique-id='" + ID_FACTURE_Unique + "'";
			String anoId = IdGenerator.nextId();
			String libelleLien = "Entete "+entete_numfact;
			Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
			xslParams.put("anoId", anoId);
			xslParams.put("presentation", "src");
			Anomalie ano = new Anomalie(anoId,
                                    getDocumentModel().getControlById(CTRL_ID).getId(),
                                    getDocumentModel().getControlById(CTRL_ID).getLibelle(),
                                    getDocumentModel().getDocumentId(),
                                    "FEN0052A",
                                    "FACTURE", // élément importable
                                    entete_numfact, // id élément importable
                                    localName,
                                    libelleLien,
                                    msg,
                                    getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
                                    getDocumentModel().getControlById(CTRL_ID).getSeverity(),
                                    path,
                                    xslParams);
			ano.addNode(new Node(pymtmeth_NodeId));
			anomalies.add(ano);
		}
		chars.pop();
		return null;
	
	} else if (xpath.endsWith(RETURN_ANOMALIES_PATH)){
		chars.pop();
		return anomalies;
	} else {
		chars.pop();
		return null;
	}
}

public void endDocument() throws SAXException {}

public void characters(char[] ch, int start, int length, String xpath) {
	// on stocke les caractères lus
	chars.peek().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) {}
}
