/*
 * Copyright 
 *   2005 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 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.rec;

import java.util.Hashtable;
import java.util.StringTokenizer;
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° REC05
 * Il consiste à vérifier la règle fonctionnelle suivante :
 * 		Contrôle des montants.
 * Il est fait ainsi :
 * 		1- 	Lorsqu'on lit un élément BlocBordereau :
 * 			- on vide BlocBordereau/Exer/@V, BlocBordereau/IdBord/@V, BlocBordereau/Typbord/@V, BlocBordereau/MtBordHT/@V, BlocBordereau/MtBordTVA/@V.
 * 			- on stocke BlocBordereau/Exer/@V, BlocBordereau/IdBord/@V, BlocBordereau/Typbord/@V, BlocBordereau/MtBordHT/@V, BlocBordereau/MtBordTVA/@V.
 * 		2- 	Lorsqu'on lit un élément BlocPiece :
 * 			- on vide BlocPiece/IdPce/@V.
 * 			- on stocke BlocPiece/IdPce/@V.
 * 		3- Lorsqu'on lit un élément InfoLignePiece :
 * 			- on vide InfoLignePiece/IdLigne/@V, InfoLignePiece/MtHT/@V, InfoLignePiece/MtTVA/@V.
 * 			- on stocke InfoLignePiece/IdLigne/@V, InfoLignePiece/MtHT/@V, InfoLignePiece/MtTVA/@V.
 * 		4- Lorsqu'on lit une fin d'élément BlocBordereau :
 * 			- on vérifie que BlocBordereau/MtBordHT/@V et BlocBordereau/MtBordTVA/@V. est positif.
 * 		5- Lorsqu'on lit une fin d'élément InfoLignePiece :
 * 			- on vérifie que InfoLignePiece/MtHT/@V et InfoLignePiece/MtTVA/@V est positif.
 * 
 * 
 * !!!! Attention !!!!
 * Le message de ce contrôle est double. Selon le cas, nous avons besoin de deux messages différents. 
 * Ainsi les deux messages sont concaténés et séparés par le caractère '|'
 */
public class REC05 extends AbstractUnitControl implements ConstantsControlsPESv2 {
	private final static Logger logger = Logger.getLogger(REC05.class);
    public static final transient String CTRL_ID="REC05";
	private Vector<Anomalie> anosB = new Vector<Anomalie>();
	private Vector<Anomalie> anosP = new Vector<Anomalie>();
	private Hashtable<String,Object> hParams;
	
	/**
	 * La balise du document général
	 */
	private String docId = null;
	private String bord_nodeId = null;
	private String ligne_nodeId = null;
	
	/**
	 * La chaine cible
	 */
	private static final String ON_RETURN_ANOMALIES = "/PES_RecetteAller/Bordereau/";
	private static final String FIN_BORDEREAU = ON_RETURN_ANOMALIES;
	private static final String FIN_LIGNEPIECE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/";
	private static final String FIN_PIECE = "/PES_RecetteAller/Bordereau/Piece/";
		
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */
	private String bord_Exer = "";
	private String bord_IdBord = "";
	private String bord_TypBord = "";
	private String bord_Mtht = "";
	private String bord_Mttva = "";
	private String bord_Mtht_nodeid = "";
	private String bord_Mttva_nodeid = "";
	private String piece_IdPce = "";
	private String ligne_IdLigne = "";
	private String ligne_Mtht = "";
	private String ligne_Mttva = "";
	private String ligne_Mtht_nodeid = "";
	private String ligne_Mttva_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_TYPBORD = "#BORD_TYPBORD#";
	private static final String MSG_BORD_MTHT = "#BORD_MTHT#";
	private static final String MSG_BORD_MTTVA = "#BORD_MTTVA#";
	private static final String MSG_PIECE_IDPCE = "#PIECE_IDPCE#";
	private static final String MSG_LIGNE_IDLIGNE = "#LIGNE_IDLIGNE#";
	private static final String MSG_LIGNE_MTHT = "#LIGNE_MTHT#";
	private static final String MSG_LIGNE_MTTVA = "#LIGNE_MTTVA#";
	
	/**
	 * 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_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_BLOCBORDEREAU_MTBORDHT = "/PES_RecetteAller/Bordereau/BlocBordereau/MtBordHt/";
	private static final String CHEMIN_BLOCBORDEREAU_MTBORDTVA = "/PES_RecetteAller/Bordereau/BlocBordereau/MtBordTVA/";
	
	private static final String CHEMIN_BLOCPIECE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/";
	private static final String CHEMIN_BLOCPIECE_IDPCE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/IdPce/";
														 
	private static final String CHEMIN_INFOLIGNEPIECE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/";
	private static final String CHEMIN_INFOLIGNEPIECE_IDLIGNE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/IdLigne/";
	private static final String CHEMIN_INFOLIGNEPIECE_MTHT = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/MtHT/";
	private static final String CHEMIN_INFOLIGNEPIECE_MTTVA = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/MtTVA/";
	
	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)) {
			bord_Exer = bord_IdBord = bord_TypBord = bord_Mtht = bord_Mttva = "";
			bord_nodeId = atts.getValue("ano:node-id");
			anosB = new Vector<Anomalie>();
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_EXER)) {
			bord_Exer = 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_BLOCBORDEREAU_MTBORDHT)) {
			bord_Mtht = atts.getValue("V");
			bord_Mtht_nodeid = atts.getValue("ano:node-id");
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU_MTBORDTVA)) {
			bord_Mttva = atts.getValue("V");
			bord_Mttva_nodeid = atts.getValue("ano:node-id");
		}
		
		// 2
		if (xpath.endsWith(CHEMIN_BLOCPIECE)) {
			piece_IdPce = "";
			anosP = new Vector<Anomalie>();
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_IDPCE)) {
			piece_IdPce = atts.getValue("V");
		}
		
		// 3
		if (xpath.endsWith(CHEMIN_INFOLIGNEPIECE)) {
			ligne_IdLigne = ligne_Mtht = ligne_Mttva = "";
			ligne_nodeId = atts.getValue("ano:node-id");
		}
		if (xpath.endsWith(CHEMIN_INFOLIGNEPIECE_IDLIGNE)) {
			ligne_IdLigne = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_INFOLIGNEPIECE_MTHT)) {
			ligne_Mtht = atts.getValue("V");
			ligne_Mtht_nodeid = atts.getValue("ano:node-id");
		}
		if (xpath.endsWith(CHEMIN_INFOLIGNEPIECE_MTTVA)) {
			ligne_Mttva = atts.getValue("V");
			ligne_Mttva_nodeid = atts.getValue("ano:node-id");
		}
	}
	

	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(xpath.endsWith(ON_RETURN_ANOMALIES)){
			boolean err = false;
			Vector<Node> anonodes = new Vector<Node>();
			try {
				if (bord_Mtht!=null && !"".equals(bord_Mtht)) {
					double mtHT = Double.parseDouble(bord_Mtht);
					if (mtHT <= 0) {err = true; anonodes.add(new Node (bord_Mtht_nodeid)); }
				}
// FA 37
//				if (bord_Mttva!=null && !"".equals(bord_Mttva)) {
//					double mtTVA = Double.parseDouble(bord_Mttva);
//					if (mtTVA <= 0) {err = true; anonodes.add(new Node (bord_Mttva_nodeid)); }
//				}
			} catch (Exception e) { err = true; }
			
			if (err) {
				StringTokenizer st = new StringTokenizer (getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent(), "|");
				String msg = st.nextToken();
				msg = msg.replaceAll(MSG_BORD_NUM, bord_IdBord);
				msg = msg.replaceAll(MSG_BORD_EXER, bord_Exer);
				msg = msg.replaceAll(MSG_BORD_TYPBORD, bord_TypBord);
				msg = msg.replaceAll(MSG_BORD_MTHT, bord_Mtht);
				msg = msg.replaceAll(MSG_BORD_MTTVA, bord_Mttva);
				String path="@added:primary-key='"+bord_Exer+"-"+bord_TypBord+"-"+bord_IdBord+"'";
				String anoId = IdGenerator.nextId();
				String libelleLien = "Bordereau "+bord_IdBord;
				Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
				xslParams.put("elementId", "Bordereau");
				xslParams.put("mandatId", "");
				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);
				anosB.add(ano);
			}
			return anosB;
		} else if (xpath.endsWith(FIN_PIECE)){
			return anosP;
		} else if (xpath.endsWith(FIN_LIGNEPIECE)){
			boolean err = false;
			Vector<Node> anonodes = new Vector<Node>();
			try {
				if (ligne_Mtht!=null && !"".equals(ligne_Mtht)) {
					double mtHT = Double.parseDouble(ligne_Mtht);
					if (mtHT <= 0) {err = true; anonodes.add(new Node (ligne_Mtht_nodeid)); }
				}
// FA 37
//				if (ligne_Mttva!=null && !"".equals(ligne_Mttva)) {
//					double mtTVA = Double.parseDouble(ligne_Mttva);
//					if (mtTVA <= 0) {err = true; anonodes.add(new Node (ligne_Mttva_nodeid)); }
//				}
			} catch (Exception e) { err = true; }
			
			if (err) {
				StringTokenizer st = new StringTokenizer (getDocumentModel().getControlById(CTRL_ID).getMessage().getContent(), "|");
				st.nextToken();
				String msg = st.nextToken();
				msg = msg.replaceAll(MSG_BORD_NUM, bord_IdBord);
				msg = msg.replaceAll(MSG_BORD_EXER, bord_Exer);
				msg = msg.replaceAll(MSG_BORD_TYPBORD, bord_TypBord);
				msg = msg.replaceAll(MSG_PIECE_IDPCE, piece_IdPce);
				msg = msg.replaceAll(MSG_LIGNE_IDLIGNE, ligne_IdLigne);
				msg = msg.replaceAll(MSG_LIGNE_MTHT, ligne_Mtht);
				msg = msg.replaceAll(MSG_LIGNE_MTTVA, ligne_Mttva);
				String path="@added:primary-key='"+bord_Exer+"-"+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_RECETTE, // élément importable
                                                bord_IdBord, // id élément importable
                                                localName,
                                                libelleLien,
                                                msg,
                                                getDocumentModel().getControlById(CTRL_ID).getRegle().getContent(),
                                                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);
				anosP.add(ano);
			}
			return null;
		} 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) {}
}
