/*
 * Impl�mente le contr�le N� DEP14
 * 
 * Contr�le de la pr�sence d�un mode de r�glement
 * 
 * 1 - Pour un mandat � payer, le mode de r�glement doit �tre indiqu�, et ne peut pas �tre �gal � "Autres" (ModRegl=09).
 * 2 -		Si le mode r�glement est � num�raire �, le montant ne doit pas d�passer le seuil pr�vu dans la r�glementation (au 22/08/2006 : 750 euros)
 * 3 -		Si le mode de r�glement est � virement � ou � pr�l�vement �, les coordonn�es bancaires doivent �tre renseign�es.
 * 4 - Dans le cas d'un mode de r�glement par virement bancaire, la zone libell� du virement est renseign�e.
 * 5 - 		Si le mode de r�glement � virement � l��tranger �, l�identifiant international bancaire (IBAN) doit �tre renseign�. * 
 */

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

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

	/**
	 * La balise du document g�n�ral
	 */
	private String docId = null;
	private String nodeId = null;

	/**
	 * La chaine cible
	 */
	private static final String FIN_PIECE = "/PES_DepenseAller/Bordereau/Piece/";
	private static final String FIN_LIGNEPCE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/";
	private static final String ON_RETURN_ANOMALIES = FIN_PIECE;


	/**
	 * Variables contenant les valeurs n�cessaires � ce contr�le
	 */

	private String bord_IdBord = "";
	private String bord_ExerBord = "";
	private String bord_TypBord = "";
	private String piece_IdPce = "";
	private String piece_TypPce = "";
	private String piece_NatPce = "";
	private String piece_NodeIdPce = "";
	private String lignepiece_Id = "";
	private String lignepiece_NodeId = "";
	private String lignepiece_ModeReglement = "";
	private String lignepiece_IdBanc = "";
	private String lignepiece_LibVir1 = "";
	private String lignepiece_ModeReglement_NodeId = "";
	private String lignepiece_IdBanc_NodeId = "";
	private String lignepiece_CpteBanc_NodeId = "";
	private String lignepiece_LibVir1_NodeId = "";
	private String lignepiece_CodeEtab_NodeId = "";
	private String lignepiece_CodeGuic_NodeId = "";
	private String lignepiece_CleRib_NodeId = "";
	
	
	private Double lignepiece_MtHT = 0.0;
	private Double lignepiece_MtTVA = 0.0;
	private String lignepiece_MtHT_NodeId = "";
	private String lignepiece_MtTVA_NodeId = "";
	
	private boolean cpteBancaireExist = false;
	
	private Vector<String> vIdsLigne = new Vector<String>();
	private Vector<String> vTypPceNatPceEligible = new Vector<String>();
	/**
	 * 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_TYPE = "#BORD_TYPBORD#";
	private static final String MSG_PIECE_ID = "#PIECE_IDPCE#";
	private static final String MSG_LIGNEPIECE_ID = "#LIGNE_IDLIGNE#";
	/**
	 * 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_PIECE = "/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_BLOCPIECE_IDPIECE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/IdPce/";
	private static final String CHEMIN_BLOCPIECE_TYPPIECE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/TypPce/";
	private static final String CHEMIN_BLOCPIECE_NATPIECE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/NatPce/";
	
	private static final String CHEMIN_BLOCLIGNEPIECE_IDLIGNEPIECE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/IdLigne/";
	private static final String CHEMIN_BLOCLIGNEPIECE_MODEREGLEMENT = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/ModRegl/";
	private static final String CHEMIN_BLOCLIGNEPIECE_MTHT = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/MtHT/";
	private static final String CHEMIN_BLOCLIGNEPIECE_MTTVA = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/MtTVA/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/CpteBancaire/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_IDBANC = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/CpteBancaire/IdBancInt/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_CODEETAB = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/CpteBancaire/CodeEtab/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_CODEGUIC = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/CpteBancaire/CodeGuic/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_CLERIB = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/CpteBancaire/CleRib/";
	private static final String CHEMIN_BLOCLIGNEPIECE_LIBVIR1 = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/LibVir1/";

	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
		vTypPceNatPceEligible.add("0101");vTypPceNatPceEligible.add("0102");vTypPceNatPceEligible.add("0103");vTypPceNatPceEligible.add("0104");
		vTypPceNatPceEligible.add("0105");vTypPceNatPceEligible.add("0111");vTypPceNatPceEligible.add("0115");
		vTypPceNatPceEligible.add("0207");vTypPceNatPceEligible.add("0208");
		vTypPceNatPceEligible.add("0801");vTypPceNatPceEligible.add("0802");vTypPceNatPceEligible.add("0811");vTypPceNatPceEligible.add("0815");
		vTypPceNatPceEligible.add("0901");vTypPceNatPceEligible.add("0902");vTypPceNatPceEligible.add("0913");vTypPceNatPceEligible.add("0914");
		vTypPceNatPceEligible.add("0915");
		vTypPceNatPceEligible.add("1101");vTypPceNatPceEligible.add("1102");vTypPceNatPceEligible.add("1114");vTypPceNatPceEligible.add("1115");
	}

	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_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_BLOCPIECE_IDPIECE)){
			piece_IdPce=atts.getValue("V");
			anos.clear();
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_TYPPIECE)) {
			piece_TypPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_NATPIECE)) {
			piece_NatPce = atts.getValue("V");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_IDLIGNEPIECE)){
			lignepiece_Id=atts.getValue("V");
			lignepiece_NodeId=atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_MODEREGLEMENT)){
			lignepiece_ModeReglement = atts.getValue("V");
			lignepiece_ModeReglement_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_MTHT)){
			lignepiece_MtHT_NodeId = atts.getValue("ano:node-id");
			try{
				lignepiece_MtHT = Double.parseDouble(atts.getValue("V"));
			} catch (NumberFormatException nfe){
				nfe.printStackTrace();
			}
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_MTTVA)){
			lignepiece_MtTVA_NodeId = atts.getValue("ano:node-id");
			try{
				lignepiece_MtTVA = Double.parseDouble(atts.getValue("V"));
			} catch (NumberFormatException nfe){
				nfe.printStackTrace();
			}
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE)){
			cpteBancaireExist = true;
			lignepiece_CpteBanc_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_IDBANC)){
			lignepiece_IdBanc = atts.getValue("V");
			lignepiece_IdBanc_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_LIBVIR1)){
			lignepiece_LibVir1 = atts.getValue("V");
			lignepiece_LibVir1_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_CODEETAB)){
			lignepiece_CodeEtab_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_CODEGUIC)){
			lignepiece_CodeGuic_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE_CLERIB)){
			lignepiece_CleRib_NodeId = atts.getValue("ano:node-id");
		}
		
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(xpath.endsWith(FIN_LIGNEPCE)){
			try{
				String typnat = piece_TypPce+piece_NatPce;
				// 1
				if(vTypPceNatPceEligible.contains(typnat) && (lignepiece_ModeReglement.equals("09") || lignepiece_ModeReglement.equals(""))){
					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_TYPE, bord_TypBord);
					msg = msg.replaceAll(MSG_PIECE_ID, piece_IdPce);
					msg = msg.replaceAll(MSG_LIGNEPIECE_ID, lignepiece_Id);
					String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
					String anoId = IdGenerator.nextId();
					String libelleLien = "Bordereau "+bord_IdBord+" Mandat "+piece_IdPce;
					Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
					xslParams.put("elementId","");
					xslParams.put("mandatId",piece_IdPce);
					xslParams.put("browser-destination", "internal");
					xslParams.put("anoId", anoId);
					String severity = "";
					if(lignepiece_ModeReglement.equals("")){
						severity = "NON BLOQUANT";
					}else{
						severity = getDocumentModel().getControlById(CTRL_ID).getSeverity();
					}
					Anomalie ano = new Anomalie(anoId,
							getDocumentModel().getControlById(CTRL_ID).getId(),
							getDocumentModel().getControlById(CTRL_ID).getLibelle(),
							getDocumentModel().id,
							xpath.split("/")[1],
							BORDEREAU_DEPENSE, // �l�ment importable
							bord_IdBord, // id �l�ment importable
							localName,
							libelleLien,
							msg,
							getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
							severity,
							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.addNode(new Node(lignepiece_ModeReglement_NodeId));
					anos.add(ano);
				// 2
				}else if(vTypPceNatPceEligible.contains(typnat) && (lignepiece_ModeReglement.equals("01") && ((lignepiece_MtHT+lignepiece_MtTVA)>750))){
					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_TYPE, bord_TypBord);
					msg = msg.replaceAll(MSG_PIECE_ID, piece_IdPce);
					msg = msg.replaceAll(MSG_LIGNEPIECE_ID, lignepiece_Id);
					String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
					String anoId = IdGenerator.nextId();
					String libelleLien = "Bordereau "+bord_IdBord+" Mandat "+piece_IdPce;
					Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
					xslParams.put("elementId","");
					xslParams.put("mandatId",piece_IdPce);
					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().id,
							xpath.split("/")[1],
							BORDEREAU_DEPENSE, // �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.addNode(new Node(lignepiece_MtHT_NodeId));
					ano.addNode(new Node(lignepiece_MtTVA_NodeId));
					anos.add(ano);
				// 3
				}else if(vTypPceNatPceEligible.contains(typnat) && ((lignepiece_ModeReglement.equals("03")
						|| lignepiece_ModeReglement.equals("04")
						|| lignepiece_ModeReglement.equals("05")
						|| lignepiece_ModeReglement.equals("06")
						|| lignepiece_ModeReglement.equals("10")) && !cpteBancaireExist)){
						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_TYPE, bord_TypBord);
						msg = msg.replaceAll(MSG_PIECE_ID, piece_IdPce);
						msg = msg.replaceAll(MSG_LIGNEPIECE_ID, lignepiece_Id);
						String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
						String anoId = IdGenerator.nextId();
						String libelleLien = "Bordereau "+bord_IdBord+" Mandat "+piece_IdPce;
						Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
						xslParams.put("elementId","");
						xslParams.put("mandatId",piece_IdPce);
						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().id,
								xpath.split("/")[1],
								BORDEREAU_DEPENSE, // �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.addNode(new Node(lignepiece_CpteBanc_NodeId));
						anos.add(ano);
				// 4
				}else if(vTypPceNatPceEligible.contains(typnat) && ((lignepiece_ModeReglement.equals("03")
						|| lignepiece_ModeReglement.equals("04")
						|| lignepiece_ModeReglement.equals("05")
						|| lignepiece_ModeReglement.equals("06")) && lignepiece_LibVir1.equals(""))){
						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_TYPE, bord_TypBord);
						msg = msg.replaceAll(MSG_PIECE_ID, piece_IdPce);
						msg = msg.replaceAll(MSG_LIGNEPIECE_ID, lignepiece_Id);
						String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
						String anoId = IdGenerator.nextId();
						String libelleLien = "Bordereau "+bord_IdBord+" Mandat "+piece_IdPce;
						Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
						xslParams.put("elementId","");
						xslParams.put("mandatId",piece_IdPce);
						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().id,
								xpath.split("/")[1],
								BORDEREAU_DEPENSE, // �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.addNode(new Node(lignepiece_LibVir1_NodeId));
						anos.add(ano);
				// 5
				} else if(vTypPceNatPceEligible.contains(typnat) && (lignepiece_ModeReglement.equals("06") && lignepiece_IdBanc.equals(""))){
					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_TYPE, bord_TypBord);
					msg = msg.replaceAll(MSG_PIECE_ID, piece_IdPce);
					msg = msg.replaceAll(MSG_LIGNEPIECE_ID, lignepiece_Id);
					String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
					String anoId = IdGenerator.nextId();
					String libelleLien = "Bordereau "+bord_IdBord+" Mandat "+piece_IdPce;
					Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
					xslParams.put("elementId","");
					xslParams.put("mandatId",piece_IdPce);
					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().id,
							xpath.split("/")[1],
							BORDEREAU_DEPENSE, // �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.addNode(new Node(lignepiece_CpteBanc_NodeId));
					anos.add(ano);
				}
			} catch (NumberFormatException nfe){
				nfe.printStackTrace();
			}
			lignepiece_ModeReglement="";
			return null;
		}else if(xpath.endsWith(ON_RETURN_ANOMALIES)){
			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) {}
}
