/*
 * Copyright 
 *   2008 axYus - www.axyus.com
 *   2008 C ESCOBAR - christel.escobar@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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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.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 DEP19 extends AbstractUnitControl implements ConstantsControlsPESv2{
	
/**
 * Implémente le contrôle N° DEP19
 * 
 * Contrôle de présence du numéro d’inventaire
 * 
 * Vérifier pour tous les mandats, si Piece/ BlocPiece/ InfoPce/ TypPce[@V] vaut 03 ou 04, alors :
 *   1) aucunes de ses lignes ne doit avoir de bloc LigneDePiece/ Tiers/CpteBancaire (BLOQUANT).
 *   2)	toutes ses lignes doivent avoir un tiers dont la CatTiers vaut 20 et NatJur 07.
 * 
 */
	
	private final static Logger logger = Logger.getLogger(DEP19.class);
	public static final transient String CTRL_ID = "DEP19";
	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 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 lignepiece_Id = "";
	private String lignepiece_TypPce_NodeId = "";
	private String lignepiece_CatTiers = "";
//	private String lignepiece_CpteTiers_NodeId = "";
	private String lignepiece_CatTiers_NodeId = "";
	private String lignepiece_NatJur = "";
	private String lignepiece_NatJur_NodeId = "";
	private String lignepiece_CpteBancaire = "";
	private String lignepiece_CpteBancaire_NodeId = "";

	private Vector<Triplet> vLigneIdCatTiersNatJurNodeId = new Vector<Triplet>();

	/**
	 * 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/Piece/";
	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_LIGNEPIECE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/";
	private static final String CHEMIN_BLOCLIGNEPIECE_ID = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/IdLigne/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CATTIERS  = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/CatTiers/";
	private static final String CHEMIN_BLOCLIGNEPIECE_NATJUR  = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/NatJur/";
	private static final String CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/Tiers/CpteBancaire/";
	
	
	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
	}

	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_PIECE)) {
			lignepiece_TypPce_NodeId = "";
			anos.clear();
			vLigneIdCatTiersNatJurNodeId.clear();
		}
		if(xpath.endsWith(CHEMIN_BLOCPIECE_IDPIECE)){
			piece_IdPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_LIGNEPIECE)) {
			lignepiece_CatTiers_NodeId = lignepiece_CpteBancaire_NodeId = lignepiece_NatJur_NodeId = "";
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CATTIERS)){
			lignepiece_CatTiers = atts.getValue("V");
			lignepiece_CatTiers_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_CPTEBANCAIRE)){
			lignepiece_CpteBancaire = "OK";
			lignepiece_CpteBancaire_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_NATJUR)){
			lignepiece_NatJur = atts.getValue("V");
			lignepiece_NatJur_NodeId= atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCPIECE_TYPPIECE)){
			piece_TypPce = atts.getValue("V");
			lignepiece_TypPce_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_ID)){
			lignepiece_Id = atts.getValue("V");
		}
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(xpath.endsWith(LIGNEPCE)){
			Vector<String> nodes = new Vector<String>();
			boolean err = false;
			String severity = getDocumentModel().getControlById(CTRL_ID).getSeverity();
			if(piece_TypPce.equals("03") || piece_TypPce.equals("04")){
				if(!lignepiece_CpteBancaire.equals("")){
					severity="BLOQUANT";
					nodes.add(lignepiece_CpteBancaire_NodeId);
					if(err == false)err=true;
				}
				if(!lignepiece_CatTiers.equals("20")){
					nodes.add(lignepiece_CatTiers_NodeId);
					if(err == false)err=true;
				}
				if(!lignepiece_NatJur.equals("07")){
					nodes.add(lignepiece_NatJur_NodeId);
					if(err == false)err=true;
				}
				if(err == true){
					nodes.add(lignepiece_TypPce_NodeId);
//					nodes.add(lignepiece_CpteTiers_NodeId);
					vLigneIdCatTiersNatJurNodeId.add(new Triplet(lignepiece_Id, severity, nodes));
				}
			}

			lignepiece_CatTiers = lignepiece_CpteBancaire = lignepiece_NatJur = "";
			return null;
		}else if(xpath.endsWith(ON_RETURN_ANOMALIES)){
			if(piece_TypPce.equals("03") || piece_TypPce.equals("04")){
				for(Triplet t:vLigneIdCatTiersNatJurNodeId){
					String ligneId = t.lignePceId;
					String severity = t.severity;
					Vector<String> vNodes = t.v;
					
					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, ligneId);
					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(),
							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
					for(String n:vNodes){
						ano.addNode(new Node(n));
					}
					anos.add(ano);
				}
			
			}
			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) {}

	private class Triplet{
		private String lignePceId;
		private String severity;
		private Vector<String> v = new Vector<String>();
		private Triplet (String idligne,String sev,Vector<String> nodes){
			this.lignePceId = idligne;
			this.severity = sev;
			this.v = nodes;
		}
	}
}
