/*
 * 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 BigDecimal bord_MtBordHT;
	private BigDecimal bord_MtBordTVA;
	private BigDecimal 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,BigDecimal> hashMtsBord = new Hashtable<String,BigDecimal>();

	/**
	 * 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)) {
                    try {
			bord_MtBordHT = new BigDecimal(atts.getValue("V"));
                    }catch(Exception ex) {}
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTTVABORD)) {
                    try {
			bord_MtBordTVA = new BigDecimal(atts.getValue("V"));
                    }catch(Exception ex) {}
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTHTPIECE)) {
			if(hashMtsBord.get(BALISE_MT_HT_PIECE)!=null){
				try{
					BigDecimal oldValue = hashMtsBord.get(BALISE_MT_HT_PIECE);
					BigDecimal newValue = new BigDecimal(atts.getValue("V")).add(oldValue);
					hashMtsBord.put(BALISE_MT_HT_PIECE,newValue);
				}catch (NumberFormatException nfe){
					nfe.printStackTrace();
					logger.debug("Pb de parsing de float dans DEP03.");
				}
			}else{
                            BigDecimal value = new BigDecimal(atts.getValue("V"));
				hashMtsBord.put(BALISE_MT_HT_PIECE,value);
			}
		}
		if(CTRL_TVA){
			if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTTVAPIECE)) {
				if(hashMtsBord.get(BALISE_MT_TVA_PIECE)!=null){
					try{
						BigDecimal oldValue = hashMtsBord.get(BALISE_MT_TVA_PIECE);
						BigDecimal newValue = new BigDecimal(atts.getValue("V")).add(oldValue);
						hashMtsBord.put(BALISE_MT_TVA_PIECE,newValue);
					}catch (NumberFormatException nfe){
						nfe.printStackTrace();
						logger.debug("Pb de parsing de float dans DEP03.");
					}
				}else{
                                    BigDecimal value = new BigDecimal(atts.getValue("V"));
					hashMtsBord.put(BALISE_MT_TVA_PIECE,value);
				}
			}
		}
	}


	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 && bord_MtBordHT!=null && bord_MtBordTVA!=null && hashMtsBord.get(BALISE_MT_HT_PIECE)!=null){
					if ((!hashMtsBord.get(BALISE_MT_HT_PIECE).equals(bord_MtBordHT)) 
						|| (!hashMtsBord.get(BALISE_MT_TVA_PIECE).equals(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!=null? bord_MtBordHT.toString() : ""));
						msg = msg.replaceAll(MSG_BORD_MTTVA, (bord_MtBordTVA!=null ? bord_MtBordTVA.toString():""));
						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 (!(hashMtsBord.get(BALISE_MT_HT_PIECE).equals(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!=null?bord_MtBordHT.toString():""));
						msg = msg.replaceAll(MSG_BORD_MTTVA, (bord_MtBordTVA!=null ? bord_MtBordTVA.toString():""));
						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 (!(hashMtsBord.get(BALISE_MT_HT_PIECE).equals(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!=null?bord_MtBordHT.toString():""));
					msg = msg.replaceAll(MSG_BORD_MTTVA, (bord_MtBordTVA!=null?bord_MtBordTVA.toString():""));
					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) {}
}
