/*
 * 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.Enumeration;
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° REC07
 * 
 * Contrôle de l’absence de doublon sur le numéro de pièce
 * 
 * Il ne doit pas y avoir de doublons sur le numéro de la pièce.
 * 
 * Tous les Piece/BlocPiece/InfoPce/IdPce[@V] doivent être différents pour un même BlocBordereau/Exer[@V] et même BlocBordereau/TypBord[@V]
 * 
 * 
 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 * On n'utilise pas le paramètre PAR1
 * (bde le 27/03/2007)
 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 */
public class REC07 extends AbstractUnitControl implements ConstantsControlsPESv2 {
	private final static Logger logger = Logger.getLogger(REC07.class);
    public static final transient String CTRL_ID="REC07";
	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_RecetteAller/Bordereau/";
	private static final String FIN_INFOPCE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/";
	private static final String ON_RETURN_ANOMALIES = "/PES_RecetteAller/";
	

	/**
	 * 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_NodeIdPce = "";
	private Hashtable<String, Vector<String>>pieces = new Hashtable<String, Vector<String>>(); 
	
//	private Hashtable<String,Pair> hashIdsPiece = new Hashtable<String,Pair>();
//	private Vector<Quadruplet> vIdsPiece= new Vector<Quadruplet>();// stockage des id de piece en defaut
	private Vector<Node> anonodes = new Vector<Node>();
	/**
	 * 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_IDPIECE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/IdPce/";


	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>();
			piece_IdPce = piece_NodeIdPce = "";
		}
		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)){
			piece_IdPce=atts.getValue("V");
			piece_NodeIdPce=atts.getValue("ano:node-id");
		}
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(xpath.endsWith(FIN_INFOPCE)){
			String clef = bord_ExerBord+"|"+bord_TypBord+"|"+piece_IdPce;
			Vector<String> tmp = pieces.get(clef);
			if (tmp==null) {tmp = new Vector<String>(); pieces.put(clef, tmp); }
			tmp.add(bord_IdBord+"|"+piece_NodeIdPce+"|0");		
			
			return null;
		}else if(xpath.endsWith(FIN_BORDEREAU)){
			for (Enumeration<String> e = pieces.keys(); e.hasMoreElements();) {
				String clef = (String)e.nextElement();
				Vector<String> v = pieces.get(clef);
				if (v.size()>1) {
					StringTokenizer st = new StringTokenizer (clef, "|");
					String _bord_ExerBord = st.nextToken();
					String _bord_TypBord = st.nextToken();
					String _idPce = st.nextToken();
					
					String msgRef = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
					StringBuffer msg = new StringBuffer();
					msg.append("<ul>");
					Vector<Node> anonodesid = new Vector<Node>();
					int i=0;
					for (String clef2:v) {
						StringTokenizer st2 = new StringTokenizer(clef2, "|");
						String _bord_IdBord = st2.nextToken();
						String _piece_NodeIdPce = st2.nextToken();
						String anoCree = st2.nextToken();
						msg.append("<li>").append (msgRef.replaceAll(MSG_BORD_EXER, _bord_ExerBord).replaceAll(MSG_BORD_NUM, _bord_IdBord).replaceAll(MSG_BORD_TYPE, _bord_TypBord).replaceAll(MSG_PIECE_ID, _idPce)).append ("</li>");
						anonodesid.add (new Node(_piece_NodeIdPce));

						if (i>0 && "0".equals(anoCree)) {
							msg.append ("</ul>");
							String path="@added:primary-key='"+_bord_ExerBord+"-"+_bord_TypBord+"-"+_bord_IdBord+"'";
							String anoId = IdGenerator.nextId();
							String libelleLien = "Bordereau "+_bord_IdBord+" Mandat "+_idPce;
							Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
							xslParams.put("elementId","Bordereau");
							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.toString(),
									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(anonodesid);
							anos.add(ano);
							
							// indicateur que l'ano a été créée pour cette pièce
							String tmp = _bord_IdBord+"|"+_piece_NodeIdPce+"|1";
							v.remove(clef2);
							v.add(tmp);
						}
						i++;
					}
				}
			}
			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 Quadruplet{
		private String exercice,typbordereau,idbordereau,idPiece;
		private Quadruplet(String exercice,String typbordereau,String idbordereau,String idPiece){
			this.exercice=exercice;
			this.typbordereau=typbordereau;
			this.idbordereau=idbordereau;
			this.idPiece=idPiece;
		}
	}	
}
