/*
 * Impl�mente le contr�le N� DEP03
 * 
 * Contr�le de coh�rence des montants du bordereau
 * 
 * Le montant total, HT et TVA, du bordereau de mandats doit �tre �gal � la somme des montants des mandats, HT et TVA.
 * 
 * Pour chaque bordereau v�rifier que BlocBordereau/MtBordHT[@V] = somme des Piece/LigneDePiece/BlocLignePiece/InfoLignePce/MtHT[@V]
 * 
 * Pour chaque bordereau v�rifier que BlocBordereau/MtBordTVA[@V] = somme des Piece/LigneDePiece/BlocLignePiece/InfoLignePce/MtTVA[@V] 
 * (si MtBordTVA pas renseign�, ne pas faire le test)
 * 
 */

package fr.gouv.finances.cp.xemelios.controls.pesv2.dep;

import java.math.BigDecimal;
import java.text.DecimalFormat;
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;
import fr.gouv.finances.cp.xemelios.controls.pesv2.ConstantsControlsPESv2;

public class DEP03 extends AbstractUnitControl implements ConstantsControlsPESv2{
	private final static Logger logger = Logger.getLogger(DEP03.class);
	public static final transient String CTRL_ID = "DEP03";
	private Vector<Anomalie> anos = new Vector<Anomalie>();
	private Hashtable<String,Object> hParams;

	/**
	 * La balise du document g�n�ral
	 */
	private String docId = null;
	private ArrayList<Node> nodesId = new ArrayList<Node>();

	/**
	 * La chaine cible
	 */
	private static final String FIN_BORDEREAU = "/PES_DepenseAller/Bordereau/";
	private static final String ON_RETURN_ANOMALIES = FIN_BORDEREAU;
	/**
	 * Variables contenant les valeurs n�cessaires � ce contr�le
	 */
	private String bord_ExerBord = "";
	private String bord_IdBord = "";
	private String bord_TypBord = "";
	private String bord_MtBordHT = "";
	private String bord_MtBordTVA = "";
	private String bord_NodeIdBord = "";

	private static final String KEY_HASHTABLE_MT_HT = "MTBORDHT";
	private static final String KEY_HASHTABLE_MT_TVA = "MTBORDTVA";
	private static final String BALISE_MT_HT_PIECE = "MtHT";
	private static final String BALISE_MT_TVA_PIECE = "MtTVA";
	private static boolean CTRL_TVA = false;
	private static DecimalFormat df;
	
	private Hashtable<String,Object> hashMtsBord = new Hashtable<String,Object>();

	/**
	 * Variables devant �tre remplac�es dans le message
	 */
	private static final String MSG_BORD_NUM = "#BORD_NUM#";
	private static final String MSG_BORD_EXER = "#BORD_EXER#";
	private static final String MSG_BORD_TYPEBORD = "#BORD_TYPE#";
	private static final String MSG_BORD_MTHT = "#BORD_MT_HT#";
	private static final String MSG_BORD_SOMMEHTPIECE = "#BORD_SOMME_HT_PIECE#";
	private static final String MSG_BORD_MTTVA = "#BORD_MT_TVA#";
	private static final String MSG_BORD_SOMMETVAPIECE = "#BORD_SOMME_TVA_PIECE#";
	/**
	 * Chemins incomplet vers les divers �l�ments que l'on veux lire. Ils sont incomplets dans la mesure 
	 * o� on n'a pas le d�but du chemin, vu que ce contr�le est utilis� pour les D�penses uniquement
	 */
	private static final String CHEMIN_BLOCBORDEREAU = "/PES_DepenseAller/Bordereau/BlocBordereau/";
	private static final String CHEMIN_BORDEREAU = "/PES_DepenseAller/Bordereau/";
	private static final String CHEMIN_BLOCBORDEREAU_EXER = "/PES_DepenseAller/Bordereau/BlocBordereau/Exer/";
	private static final String CHEMIN_BLOCBORDEREAU_IDBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/IdBord/";
	private static final String CHEMIN_BLOCBORDEREAU_TYPBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/TypBord/";
	private static final String CHEMIN_BLOCBORDEREAU_MTHTBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/MtBordHT/";
	private static final String CHEMIN_BLOCBORDEREAU_MTHTPIECE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/MtHT/";
	private static final String CHEMIN_BLOCBORDEREAU_MTTVABORD = "/PES_DepenseAller/Bordereau/BlocBordereau/MtBordTVA/";
	private static final String CHEMIN_BLOCBORDEREAU_MTTVAPIECE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/MtTVA/";

	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
		df = new DecimalFormat("############0.00");
		if(Boolean.parseBoolean(hParams.get("coltva").toString())){
			CTRL_TVA=true;
		}
	}

	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_BLOCBORDEREAU)) {
			anos = new Vector<Anomalie>();
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTHTBORD) || xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTHTPIECE) || 
				xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTTVABORD) || xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTTVAPIECE)) {
			nodesId.add(new Node(atts.getValue("ano:node-id")));
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_EXER)) {
			bord_ExerBord = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_IDBORD)) {
			bord_IdBord = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_TYPBORD)) {
			bord_TypBord = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTHTBORD)) {
			bord_MtBordHT = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTTVABORD)) {
			bord_MtBordTVA = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTHTPIECE)) {
			if(hashMtsBord.get(BALISE_MT_HT_PIECE)!=null){
				try{
					BigDecimal oldValue = new BigDecimal(hashMtsBord.get(BALISE_MT_HT_PIECE).toString());
					String newValue = new BigDecimal(atts.getValue("V")).add(oldValue).toString();
					hashMtsBord.put(BALISE_MT_HT_PIECE,newValue);
				}catch (NumberFormatException nfe){
					nfe.printStackTrace();
					logger.debug("Pb de parsing de float dans DEP03.");
				}
			}else{
				hashMtsBord.put(BALISE_MT_HT_PIECE,atts.getValue("V"));
			}
		}
		if(CTRL_TVA){
			if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTTVAPIECE)) {
				if(hashMtsBord.get(BALISE_MT_TVA_PIECE)!=null){
					try{
						BigDecimal oldValue = new BigDecimal(hashMtsBord.get(BALISE_MT_TVA_PIECE).toString());
						String newValue = new BigDecimal(atts.getValue("V")).add(oldValue).toString();
						hashMtsBord.put(BALISE_MT_TVA_PIECE,newValue);
					}catch (NumberFormatException nfe){
						nfe.printStackTrace();
						logger.debug("Pb de parsing de float dans DEP03.");
					}
				}else{
					hashMtsBord.put(BALISE_MT_TVA_PIECE,new BigDecimal(atts.getValue("V")).toString());
				}
			}
		}
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(xpath.endsWith(ON_RETURN_ANOMALIES)){
			// V�rification d'un mt tva de bordereeau
			if(CTRL_TVA){
				if(hashMtsBord.get(BALISE_MT_TVA_PIECE)!=null){
					if ((!(new BigDecimal(hashMtsBord.get(BALISE_MT_HT_PIECE).toString())).equals(new BigDecimal(bord_MtBordHT))) 
						|| (!(new BigDecimal(hashMtsBord.get(BALISE_MT_TVA_PIECE).toString())).equals(new BigDecimal(bord_MtBordTVA)))) {
						String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
						msg = msg.replaceAll(MSG_BORD_NUM, bord_IdBord);
						msg = msg.replaceAll(MSG_BORD_EXER, bord_ExerBord);
						msg = msg.replaceAll(MSG_BORD_TYPEBORD, bord_TypBord);
						msg = msg.replaceAll(MSG_BORD_MTHT, bord_MtBordHT);
						msg = msg.replaceAll(MSG_BORD_MTTVA, bord_MtBordTVA);
						msg = msg.replaceAll(MSG_BORD_SOMMEHTPIECE, hashMtsBord.get(BALISE_MT_HT_PIECE).toString());
						msg = msg.replaceAll(MSG_BORD_SOMMETVAPIECE, hashMtsBord.get(BALISE_MT_TVA_PIECE).toString());
						String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
						String anoId = IdGenerator.nextId();
						String libelleLien = "Bordereau "+bord_IdBord;
						Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
						xslParams.put("elementId","Bordereau");
						xslParams.put("browser-destination", "internal");
						xslParams.put("anoId", anoId);
						Anomalie ano = new Anomalie(anoId,
								getDocumentModel().getControlById(CTRL_ID).getId(),
								getDocumentModel().getControlById(CTRL_ID).getLibelle(),
								getDocumentModel().getDocumentId(),
								xpath.split("/")[1],
								"Bordereau", // �l�ment importable
								bord_IdBord, // id �l�ment importable
								localName,
								libelleLien,
								msg,
								getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
								getDocumentModel().getControlById(CTRL_ID).getSeverity(),
								path, // xpath vers le bordereau 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);
					}
				}else{
					if (!(new BigDecimal(hashMtsBord.get(BALISE_MT_HT_PIECE).toString())).equals(new BigDecimal(bord_MtBordHT))) {
						
						String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
						msg = msg.replaceAll(MSG_BORD_NUM, bord_IdBord);
						msg = msg.replaceAll(MSG_BORD_EXER, bord_ExerBord);
						msg = msg.replaceAll(MSG_BORD_TYPEBORD, bord_TypBord);
						msg = msg.replaceAll(MSG_BORD_MTHT, bord_MtBordHT);
						msg = msg.replaceAll(MSG_BORD_MTTVA, bord_MtBordTVA);
						msg = msg.replaceAll(MSG_BORD_SOMMEHTPIECE, hashMtsBord.get(BALISE_MT_HT_PIECE).toString());
						msg = msg.replaceAll(MSG_BORD_SOMMETVAPIECE, "");
						String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
						String anoId = IdGenerator.nextId();
						String libelleLien = "Bordereau "+bord_IdBord;
						Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
						xslParams.put("elementId","Bordereau");
						xslParams.put("browser-destination", "internal");
						xslParams.put("anoId", anoId);
						Anomalie ano = new Anomalie(anoId,
								getDocumentModel().getControlById(CTRL_ID).getId(),
								getDocumentModel().getControlById(CTRL_ID).getLibelle(),
								getDocumentModel().getDocumentId(),
								xpath.split("/")[1],
								"Bordereau", // �l�ment importable
								bord_IdBord, // id �l�ment importable
								localName,
								libelleLien,
								msg,
								getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
								getDocumentModel().getControlById(CTRL_ID).getSeverity(),
								path, // xpath vers le bordereau 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);
					}
				}
			}else{
				if (!(new BigDecimal(hashMtsBord.get(BALISE_MT_HT_PIECE).toString())).equals(new BigDecimal(bord_MtBordHT))) {
					
					String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
					msg = msg.replaceAll(MSG_BORD_NUM, bord_IdBord);
					msg = msg.replaceAll(MSG_BORD_EXER, bord_ExerBord);
					msg = msg.replaceAll(MSG_BORD_TYPEBORD, bord_TypBord);
					msg = msg.replaceAll(MSG_BORD_MTHT, bord_MtBordHT);
					msg = msg.replaceAll(MSG_BORD_MTTVA, bord_MtBordTVA);
					msg = msg.replaceAll(MSG_BORD_SOMMEHTPIECE, new BigDecimal(hashMtsBord.get(BALISE_MT_HT_PIECE).toString()).toString());
					msg = msg.replaceAll(MSG_BORD_SOMMETVAPIECE, "");
					String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
					String anoId = IdGenerator.nextId();
					String libelleLien = "Bordereau "+bord_IdBord;
					Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
					xslParams.put("elementId","Bordereau");
					xslParams.put("browser-destination", "internal");
					xslParams.put("anoId", anoId);
					Anomalie ano = new Anomalie(anoId,
							getDocumentModel().getControlById(CTRL_ID).getId(),
							getDocumentModel().getControlById(CTRL_ID).getLibelle(),
							getDocumentModel().getDocumentId(),
							xpath.split("/")[1],
							"Bordereau", // �l�ment importable
							bord_IdBord, // id �l�ment importable
							localName,
							libelleLien,
							msg,
							getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
							getDocumentModel().getControlById(CTRL_ID).getSeverity(),
							path, // xpath vers le bordereau 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);
				}
			}
			hashMtsBord.clear();
			nodesId.clear();
			return anos;
		} else {
			return null;
		}
	}

	public void endDocument() throws SAXException {}

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

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