/*
 * Implémente le contrôle N° DEP07
 * 
 * Règle de valorisation de la Nature de la pièce
 * 
 * 1-	Pour les nomenclatures M14 -M21 -M52 -M61 - M31 - M71, si le type de la pièce est ordre mixte, le compte de tiers est seul vérifié.
 * 2-	SI 
 * 			au moins une ligne du mandat contient un compte par nature typé ‘Paie’ (64*), ALORS la nature du mandat doit être valorisé à ‘Paie’.
 * 		SINON 
 * 			SI 
 * 				la première ligne du mandat contient une référence Régie ALORS la nature du mandat doit être valorisé à ‘Régie’.
 * 
 */

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 DEP07 extends AbstractUnitControl implements ConstantsControlsPESv2{
	private final static Logger logger = Logger.getLogger(DEP07.class);
	public static final transient String CTRL_ID = "DEP07";
	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_BORDEREAU = "/PES_DepenseAller/Bordereau/";
	private static final String FIN_LIGNEPCE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/";
	private static final String ON_RETURN_ANOMALIES = "/PES_DepenseAller/Bordereau/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_NatPce = "";
	private String piece_TypPce = "";

	private String piece_NodeIdNatPce = "";

	private String ligneDePiece_Nature = "";
	private String ligneDePiece_Regie = "";
	private String ligneDePiece_NodeIdRegie = "";
	private String ligneDePiece_FirstNodeIdRegie = "";
	private String ligneDePiece_NodeIdNomTiers = "";
	private static int cptNbRegie = 0;
	
	private Vector<String> vligneDePiece_NodeIdNature64;
	
	private static String code_Nomenclature = "";
	private static boolean blocTiersExist = false;
	private static boolean ligneDePieceNatureBegin64 = false;
	private static boolean oneLigneDePieceRegie = false;
	
	private Vector<String> listePossible = 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_PIECE_TYP = "#PIECE_TYPPCE#";
	private static final String MSG_PIECE_NAT = "#PIECE_NATPCE#";

	/**
	 * 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_BLOCBORDEREAU_EXER = "/PES_DepenseAller/Bordereau/BlocBordereau/Exer/";
	private static final String CHEMIN_BLOCBORDEREAU_IDBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/IdBord/";
	private static final String CHEMIN_TIERS = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/";
	private static final String CHEMIN_TIERS_NOM = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/Nom/";
	private static final String CHEMIN_BLOCPIECE_IDPIECE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/IdPce/";
	private static final String CHEMIN_BLOCBORDEREAU_TYPBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/TypBord/";
	private static final String CHEMIN_BLOCBORDEREAU_TYPPCE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/TypPce/";
	private static final String CHEMIN_BLOCBORDEREAU_NATPCE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/NatPce/";
	
	private static final String CHEMIN_LIGNEDEPIECE_NATURE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/Nature/";
	private static final String CHEMIN_LIGNEDEPIECE_REGIE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/LiensIdent/IdRegie/";
	
	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
		code_Nomenclature=hParams.get("nomencl").toString();
		vligneDePiece_NodeIdNature64 = new Vector<String>();
		
		listePossible.add("M14");listePossible.add("M21");listePossible.add("M52");
		listePossible.add("M61");listePossible.add("M31");listePossible.add("M71");
	}

	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>();
			//anos.clear();
		}
		if(xpath.endsWith(CHEMIN_TIERS)){
			blocTiersExist=true;
		}
		if(xpath.endsWith(CHEMIN_TIERS_NOM)){
			ligneDePiece_NodeIdNomTiers=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_BLOCPIECE_IDPIECE)) {
			anos.clear();
			piece_IdPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_TYPPCE)) {
			piece_TypPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_NATPCE)) {
			piece_NatPce = atts.getValue("V");
			piece_NodeIdNatPce = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_LIGNEDEPIECE_NATURE)){
			ligneDePiece_Regie="";
			ligneDePiece_Nature=atts.getValue("V");
			if(ligneDePiece_Nature.matches("64.*")){
				vligneDePiece_NodeIdNature64.add(atts.getValue("ano:node-id"));
			}
		}
		if(xpath.endsWith(CHEMIN_LIGNEDEPIECE_REGIE)&&!oneLigneDePieceRegie){
			
			oneLigneDePieceRegie=true;
			
			cptNbRegie++;
			if(cptNbRegie==1){
				ligneDePiece_FirstNodeIdRegie=atts.getValue("ano:node-id");;
			}
			
			ligneDePiece_Regie=atts.getValue("V");
			ligneDePiece_NodeIdRegie=atts.getValue("ano:node-id");
		}
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(xpath.endsWith(FIN_LIGNEPCE)){
			// 1-
			if(listePossible.contains(code_Nomenclature) && piece_TypPce.equals("04")){
				if(!blocTiersExist){
					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_PIECE_TYP, piece_TypPce);
					msg = msg.replaceAll(MSG_PIECE_NAT, piece_NatPce);
					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().getDocumentId(),
							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(piece_NodeIdNatPce));
					ano.addNode(new Node(ligneDePiece_NodeIdNomTiers));
					anos.add(ano);
				}
			}
			// -2
			if(ligneDePiece_Nature.matches("64.*") && !ligneDePieceNatureBegin64){
				ligneDePieceNatureBegin64=true;
				if(!piece_NatPce.matches("11")){
					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_PIECE_TYP, piece_TypPce);
					msg = msg.replaceAll(MSG_PIECE_NAT, piece_NatPce);
					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().getDocumentId(),
							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(piece_NodeIdNatPce));
					for(String nodeid:vligneDePiece_NodeIdNature64){
						ano.addNode(new Node(nodeid));
					}
					anos.add(ano);
				}
			} else if(!ligneDePiece_Regie.matches("")){
				if(!piece_NatPce.matches("05")){
					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_PIECE_TYP, piece_TypPce);
					msg = msg.replaceAll(MSG_PIECE_NAT, piece_NatPce);
					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().getDocumentId(),
							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(piece_NodeIdNatPce));
					ano.addNode(new Node(ligneDePiece_FirstNodeIdRegie));
					anos.add(ano);
				}
			}
			blocTiersExist=false;
			return null;
		}else if(xpath.endsWith(ON_RETURN_ANOMALIES)){
			
			ligneDePieceNatureBegin64=false;
			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) {}
}
