/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 N LE CORRE - nicolas.lecorre@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 Lesser General Public License as published by
 * the Free Software Foundation; either version 3 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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.rec;

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;

/**
 * Implémente le contrôle N° REC10
 * 
 * Règle de valorisation de la Nature de la pièce
 * 
 * Pour chaque titre :
 *	1) Si PAR1 parmi (M14 -M21 -M52 -M61 - M31 - M71) et TypPce=04 alors présence du bloc Tiers
 *	2) Sinon si la première Piece/ LigneDePiece/ BlocLignePiece/ LiensIdent/ IdRegie[@V] est renseigné, alors NatPce=05
 *	3) Sinon si la première Piece/ LigneDePiece/ BlocLignePiece/ LiensIdent/ IdMarche [@V] est renseigné, alors NatPce=11
 *	4) Sinon si la première Piece/ LigneDePiece/ BlocLignePiece/ LiensIdent/ IdEncaissement[@V] est renseigné, alors TypPce=05
 *	5) Sinon si la première ligne contient un bloc Piece/ LigneDePiece/ BlocLignePiece/ RattachPiece avec les informations suivantes : NatPceOrig=01 et ExerRat=Exer, alors TypPce=02 et NatPce=07
 *	6) Sinon si Piece/ BlocPiece/ IdRol est renseigné alors TypPce=06.
 * 
 */
public class REC10 extends AbstractUnitControl implements ConstantsControlsPESv2 {
	private final static Logger logger = Logger.getLogger(REC10.class);
    public static final transient String CTRL_ID="REC10";
	private Vector<Anomalie> anos = new Vector<Anomalie>();
	private Hashtable<String,Object> hParams;
	
	private static final String nomenclatureAutorisee = "-M14-M21-M52-M61-M31-M71";
	/**
	 * La balise du document général
	 */
	private String docId = null;
	private String piece_NodeIdPce = null;

	/**
	 * La chaine cible
	 */
	private static final String FIN_PIECE = "/PES_RecetteAller/Bordereau/Piece/";
	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_idRol = "";
	private String piece_idRol_nodeid = "";
	private String piece_natPce_nodeid = "";
	
	private boolean premiere_ligne = true;
	
	private boolean tiers_exists = false;
	
	private boolean rattachpiece_exists = false;
	
	private String lienident_idRegie = "";
	private String lienident_idRegie_nodeid = "";
	private String lienident_idMarche = "";
	private String lienident_idMarche_nodeid = "";
	private String lienident_idEncaissement = "";
	private String lienident_idEncaissement_nodeid = "";
	
	private String rattachpiece_natPceOrig = "";
	private String rattachpiece_natPceOrig_nodeid = "";
	private String rattachpiece_exerRat = "";
	private String rattachpiece_exerRat_nodeid = "";
	
	/**
	 * 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#";

	/**
	 * 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_RecetteAller/Bordereau/BlocBordereau/";
	private static final String CHEMIN_BORDEREAU = "/PES_RecetteAller/Bordereau/";
	private static final String CHEMIN_BLOCBORDEREAU_EXER = "/PES_RecetteAller/Bordereau/BlocBordereau/Exer/";
	private static final String CHEMIN_BLOCBORDEREAU_IDBORD = "/PES_RecetteAller/Bordereau/BlocBordereau/IdBord/";
	private static final String CHEMIN_BLOCBORDEREAU_TYPBORD = "/PES_RecetteAller/Bordereau/BlocBordereau/TypBord/";
	
	private static final String CHEMIN_PIECE = "/PES_RecetteAller/Bordereau/Piece/";
	private static final String CHEMIN_BLOCPIECE_TYPPCE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/TypPce/";
	private static final String CHEMIN_BLOCPIECE_IDPIECE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/IdPce/";
	private static final String CHEMIN_BLOCPIECE_NATPCE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/NatPce/";
	private static final String CHEMIN_BLOCPIECE_IDROL = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/IdRol/";
	
	private static final String CHEMIN_LIGNE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/";
	
	private static final String CHEMIN_TIERS = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/Tiers/";
	
	private static final String CHEMIN_LIENIDENT = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/LiensIdent/";
	private static final String CHEMIN_LIENIDENT_IDREGIE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/LiensIdent/IdRegie/";
	private static final String CHEMIN_LIENIDENT_IDMARCHE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/LiensIdent/IdMarche/";
	private static final String CHEMIN_LIENIDENT_IDENCAISSEMENT = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/LiensIdent/IdEncaissement/";
	
	private static final String CHEMIN_RATTACHPIECE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/RattachPiece/";
	private static final String CHEMIN_RATTACHPIECE_NATPCEORIG = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/RattachPiece/NatPceOrig/";
	private static final String CHEMIN_RATTACHPIECE_EXERRAT = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/RattachPiece/ExerRat/";


	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) {
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU)) {
			bord_ExerBord = bord_IdBord = bord_TypBord = "";
		}
		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)) {
			anos = new Vector<Anomalie>();
			piece_IdPce = piece_natPce = piece_idRol = piece_typPce = "";
			piece_natPce_nodeid = piece_idRol_nodeid = "";
			piece_NodeIdPce = atts.getValue("ano:node-id");
			premiere_ligne = true;
			tiers_exists = false;
			rattachpiece_exists = false;
			lienident_idEncaissement = lienident_idMarche = lienident_idRegie = "";
			lienident_idEncaissement_nodeid = lienident_idMarche_nodeid = lienident_idRegie_nodeid = "";
			rattachpiece_exerRat = rattachpiece_natPceOrig = "";
			rattachpiece_exerRat_nodeid = "";
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_TYPPCE)) {
			piece_typPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_IDPIECE)) {
			piece_IdPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_NATPCE)) {
			piece_natPce_nodeid = atts.getValue("ano:node-id");
			piece_natPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_IDROL)) {
			piece_idRol = atts.getValue("V");
			piece_idRol_nodeid = atts.getValue("ano:node-id");
		}
		
		if (premiere_ligne) {
			
			if (xpath.endsWith(CHEMIN_TIERS)) {
				tiers_exists = true;
			}
			
			if (xpath.endsWith(CHEMIN_LIENIDENT)) {
				lienident_idEncaissement = lienident_idMarche = lienident_idRegie = "";
				lienident_idEncaissement_nodeid = lienident_idMarche_nodeid = lienident_idRegie_nodeid = "";
			}
			if (xpath.endsWith(CHEMIN_LIENIDENT_IDENCAISSEMENT)) {
				lienident_idEncaissement = atts.getValue("V");
				lienident_idEncaissement_nodeid = atts.getValue("ano:node-id");
			}
			if (xpath.endsWith(CHEMIN_LIENIDENT_IDMARCHE)) {
				lienident_idMarche = atts.getValue("V");
				lienident_idMarche_nodeid = atts.getValue("ano:node-id");
			}
			if (xpath.endsWith(CHEMIN_LIENIDENT_IDREGIE)) {
				lienident_idRegie = atts.getValue("V");
				lienident_idRegie_nodeid = atts.getValue("ano:node-id");
			}
			
			if (xpath.endsWith(CHEMIN_RATTACHPIECE)) {
				rattachpiece_exists = true;
				rattachpiece_exerRat = rattachpiece_natPceOrig = "";
				rattachpiece_exerRat_nodeid = "";
			}
			if (xpath.endsWith(CHEMIN_RATTACHPIECE_EXERRAT)) {
				rattachpiece_exerRat = atts.getValue("V");
				rattachpiece_exerRat_nodeid = atts.getValue("ano:node-id");
			}
			if (xpath.endsWith(CHEMIN_RATTACHPIECE_NATPCEORIG)) {
				rattachpiece_natPceOrig = atts.getValue("V");
				rattachpiece_natPceOrig_nodeid = atts.getValue("ano:node-id");
			}
		}
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if (xpath.endsWith(CHEMIN_LIGNE)) {
			premiere_ligne = false;
			return null;
		}
		else if(xpath.endsWith(ON_RETURN_ANOMALIES)){
			Vector<Node> anonodes = new Vector<Node>();
			boolean err = false;
			
			String nomencl = (String)hParams.get("nomencl");
			
			// 1) Si PAR1 parmi (M14 -M21 -M52 -M61 - M31 - M71) et TypPce=04 alors présence du bloc Tiers
			if (nomenclatureAutorisee.indexOf(nomencl)!=-1 && "04".equals(piece_typPce) & !tiers_exists) {
				err = true;
				anonodes.add(new Node(piece_NodeIdPce));
			}
			
			// 2) Sinon si la première Piece/ LigneDePiece/ BlocLignePiece/ LiensIdent/ IdRegie[@V] est renseigné, alors NatPce=05
			else if (lienident_idRegie != null && !"".equals(lienident_idRegie) && !"05".equals(piece_natPce)) {
				err = true;
				anonodes.add(new Node(lienident_idRegie_nodeid));
			}
			
			// 3) Sinon si la première Piece/ LigneDePiece/ BlocLignePiece/ LiensIdent/ IdMarche [@V] est renseigné, alors NatPce=11
			else if (lienident_idMarche != null && !"".equals(lienident_idMarche) && !"11".equals(piece_natPce)) {
				err = true;
				anonodes.add(new Node(lienident_idMarche_nodeid));
			}
			
			// 4) Sinon si la première Piece/ LigneDePiece/ BlocLignePiece/ LiensIdent/ IdEncaissement[@V] est renseigné, alors TypPce=05
			else if (lienident_idEncaissement != null && !"".equals(lienident_idEncaissement) && !"05".equals(piece_typPce)) {
				err = true;
				anonodes.add(new Node(lienident_idEncaissement_nodeid));
			}
			
			// 5) Sinon si la première ligne contient un bloc Piece/ LigneDePiece/ BlocLignePiece/ RattachPiece avec les informations suivantes : NatPceOrig=01 et ExerRat=Exer, alors TypPce=02 et NatPce=07
			else if (rattachpiece_exists && ("01".equals(rattachpiece_natPceOrig)) && (bord_ExerBord.equals(rattachpiece_exerRat)) && (!"02".equals(piece_typPce) || !"07".equals(piece_natPce))) {
				err = true;
				anonodes.add(new Node(rattachpiece_exerRat_nodeid));
				anonodes.add(new Node(rattachpiece_natPceOrig_nodeid));
			}
			
			// 6) Sinon si Piece/ BlocPiece/ IdRol est renseigné alors TypPce=06
			else if (piece_idRol != null && !"".equals(piece_idRol) && !"06".equals(piece_typPce)) {
				err = true;
				anonodes.add(new Node(piece_idRol_nodeid));
			}
			
			if (err) {
				anonodes.add(new Node(piece_natPce_nodeid));
			}
				
				
			if (err) {
				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);
				String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
				String anoId = IdGenerator.nextId();
				String libelleLien = "Bordereau "+bord_IdBord+" Titre "+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_RECETTE, // é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(anonodes);
				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) {}
}
