/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 JP.Tessier - jean-philippe.tessier@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;

/**
 * Implémente le contrôle N° DEP08
 * 
 * Contrôle lié au type de nomenclature et vote par opération
 * 
 * Les comptes Nature, Fonction et Opération doivent être renseignés selon la collectivité.
 * 
 */
public class DEP08 extends AbstractUnitControl implements ConstantsControlsPESv2{
	private final static Logger logger = Logger.getLogger(DEP08.class);
	public static final transient String CTRL_ID = "DEP08";
	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 ligneDePiece_Fonction = "";
	private String ligneDePiece_FonctionNodeId = "";
	private String ligneDePiece_Nature = "";
	private String ligneDePiece_NatureNodeId = "";
	private String ligneDePiece_Operation = "";
	private String ligneDePiece_OperationNodeId = "";
	private String ligneDePiece_Id = "";
	private String ligneDePiece_NodeId = "";
	
	private static boolean voteOperation;
	private String typeNomenclature = "";
	
	/**
	 * 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_LIGNEDEPIECE_ID = "#LIGNEDEPIECE_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_EXER = "/PES_DepenseAller/Bordereau/BlocBordereau/Exer/";
	private static final String CHEMIN_BLOCBORDEREAU_IDBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/IdBord/";
	private static final String CHEMIN_BLOCPIECE_IDPIECE = "/PES_DepenseAller/Bordereau/Piece/BlocPiece/InfoPce/IdPce/";
	private static final String CHEMIN_BLOCPIECE_LIGNEPIECE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/";
	private static final String CHEMIN_BLOCLIGNEPIECE_IDLIGNE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/IdLigne/";
	private static final String CHEMIN_BLOCBORDEREAU_TYPBORD = "/PES_DepenseAller/Bordereau/BlocBordereau/TypBord/";
	private static final String CHEMIN_LIGNEDEPIECE_FONCTION = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/Fonction/";
	private static final String CHEMIN_LIGNEDEPIECE_NATURE = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/Nature/";
	private static final String CHEMIN_LIGNEDEPIECE_OPERATION = "/PES_DepenseAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/Operation/"; 
	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
		voteOperation=Boolean.parseBoolean(hParams.get("votop").toString());
		typeNomenclature=hParams.get("typnomencl").toString();
	}

	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_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_LIGNEDEPIECE_FONCTION)){
			ligneDePiece_Fonction=atts.getValue("V");
			ligneDePiece_FonctionNodeId=atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_LIGNEDEPIECE_NATURE)){
			ligneDePiece_Nature=atts.getValue("V");
			ligneDePiece_NatureNodeId=atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_LIGNEDEPIECE_OPERATION)){
			ligneDePiece_Operation=atts.getValue("V");
			ligneDePiece_OperationNodeId=atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_IDLIGNE)){
			ligneDePiece_Id=atts.getValue("V");
			ligneDePiece_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)){
			if(ligneDePiece_Fonction.equals("") && typeNomenclature.equals("Fonction")){
					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_LIGNEDEPIECE_ID, ligneDePiece_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().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(ligneDePiece_NodeId));
					anos.add(ano);
			} else if(ligneDePiece_Nature.equals("") && typeNomenclature.equals("Nature")){
				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_LIGNEDEPIECE_ID, ligneDePiece_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().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(ligneDePiece_NodeId));
				anos.add(ano);
			} else if((ligneDePiece_Nature.equals("") || ligneDePiece_Fonction.equals("")) && typeNomenclature.matches("Nature-ref-fonct")){
				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_LIGNEDEPIECE_ID, ligneDePiece_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().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(ligneDePiece_NodeId));
				anos.add(ano);
			} else if(!voteOperation && !ligneDePiece_Operation.equals("") && !controlOperation(Integer.parseInt(ligneDePiece_Operation))){
				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_LIGNEDEPIECE_ID, ligneDePiece_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().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(ligneDePiece_OperationNodeId));
				anos.add(ano);
			}
			ligneDePiece_Fonction = ligneDePiece_FonctionNodeId = ligneDePiece_Nature = ligneDePiece_NatureNodeId = ligneDePiece_Operation = "";
			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) {}
	
	public boolean controlOperation (int i){
				
		if ( (i>0) && (i<=10) ){
			return true;
		}
		else 
			return false;
		
	}
}
