/*
 * 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 Lesser 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 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� REC06
 * Il consiste � v�rifier la r�gle fonctionnelle suivante :
 * 		Contr�le de la coh�rence du nombre de pi�ces
 * Il est fait ainsi :
 * 		1- 	Lorsqu'on lit un �l�ment BlocBordereau :
 * 			- on vide BlocBordereau/Exer/@V, BlocBordereau/IdBord/@V, BlocBordereau/NbrPce/@V.
 * 			- on stocke BlocBordereau/Exer/@V, BlocBordereau/IdBord/@V, BlocBordereau/NbrPce/@V.
 * 		2- 	Lorsqu'on lit un �l�ment Piece :
 * 			- on incr�mente le compteur de pi�ces pour ce bordereau.
 * 		3- Lorsqu'on lit une fin d'�l�ment Bordereau :
 * 			- on v�rifie que BlocBordereau/NbrPce/@V = compteurPiece.
 */
public class REC06 extends AbstractUnitControl implements ConstantsControlsPESv2 {
	private final static Logger logger = Logger.getLogger(REC06.class);
    public static final transient String CTRL_ID="REC06";
	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 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;
		
	/**
	 * Variables contenant les valeurs n�cessaires � ce contr�le
	 */
	private String bord_Exer = "";
	private String bord_IdBord = "";
	private String bord_typBord = "";
	private String bord_nbrpce = "";
	private String bord_nbrpce_nodeid = "";
	private int compteurPiece = 0;
	
	/**
	 * 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_NBPCE = "#BORD_NBPCE#";
	private static final String MSG_NB_PIECES = "#NB_PIECES#";
	
	/**
	 * 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_TYPBORD = "/PES_RecetteAller/Bordereau/BlocBordereau/TypBord/";
	private static final String CHEMIN_BLOCBORDEREAU_IDBORD = "/PES_RecetteAller/Bordereau/BlocBordereau/IdBord/";
	private static final String CHEMIN_BLOCBORDEREAU_NBRPCE = "/PES_RecetteAller/Bordereau/BlocBordereau/NbrPce/";
	
	private static final String CHEMIN_PIECE = "/PES_RecetteAller/Bordereau/Piece/";
	
	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_nbrpce = bord_nbrpce_nodeid = "";
			compteurPiece = 0;
			bord_nodeId = atts.getValue("ano:node-id");
			anos = 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_NBRPCE)) {
			bord_nbrpce = atts.getValue("V");
			bord_nbrpce_nodeid = atts.getValue("ano:node-id");
		}
		
		// 2
		if (xpath.endsWith(CHEMIN_PIECE)) {
			compteurPiece++;
		}
	}
	

	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_nbrpce!=null && !"".equals(bord_nbrpce)) {
					int nbBordPce = Integer.parseInt(bord_nbrpce);
					err = nbBordPce != compteurPiece;
				}
			} catch (Exception e) { err = true; }
			
			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_Exer);
				msg = msg.replaceAll(MSG_BORD_NBPCE, bord_nbrpce);
				msg = msg.replaceAll(MSG_NB_PIECES, String.valueOf(compteurPiece));
				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().id,
											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.addNode(new Node(bord_nbrpce_nodeid));
				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) {}
}
