/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 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 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.pj;

import java.util.ArrayList;
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° PJ2
 * Il consiste à vérifier la règle fonctionnelle suivante :
 * 
 * Les PJ contenues dans le flux doivent avoir des identifiants différents.
 * 		
 * Il est fait ainsi :
 * 
 * Les balises /PES_PJ/PJ/IdUnique doivent avoir des valeurs différentes les unes des autres
 * 		
 */
public class PJ2 extends AbstractUnitControl implements ConstantsControlsPESv2 {
	private final static Logger logger = Logger.getLogger(PJ2.class);
    public static final transient String CTRL_ID = "PJ2";
	private Hashtable<String,Object> hParams;
	
	/**
	 * La balise du document général
	 */
	private String docId = null;
	private String bord_nodeId = null;

	
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */

	private String bord_Exer = "";
	private String bord_IdBord = "";
	private String bord_TypBord = "";
	private String piece_IdPce = "";
	
	private String PJ_idPJ = "";
	private String PJ_nodeId = "";
	private ArrayList<String> valeurs_id = new ArrayList<String>();
	int compteur = 0;
	
	
	/**
	 * 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 et les Recettes
	 */
	private static final String CHEMIN_BLOCBORDEREAU = "/Bordereau/BlocBordereau/";
	private static final String CHEMIN_BLOCBORDEREAU_EXER = "/Bordereau/BlocBordereau/Exer/";
	private static final String CHEMIN_BLOCBORDEREAU_IDBORD = "/Bordereau/BlocBordereau/IdBord/";
	private static final String CHEMIN_BLOCBORDEREAU_TYPBORD = "/Bordereau/BlocBordereau/TypBord/";

	
	/**
	 * Selon que l'on est en RECETTE ou DEPENSE, le xpath est différent
	 */
	private static final String RECETTE = "PES_RecetteAller";
	private static final String DEPENSE = "PES_DepenseAller";
	private boolean depense = false;

	private static String CHEMIN_BLOCPIECE = "";
	private static String CHEMIN_BLOCPIECE_IDPCE = "";
	private static final String R_CHEMIN_BLOCPIECE = "/Bordereau/Piece/BlocPiece/";
	private static final String R_CHEMIN_BLOCPIECE_IDPCE = "/Bordereau/Piece/BlocPiece/IdPce/";
	private static final String D_CHEMIN_BLOCPIECE = "/Bordereau/Piece/BlocPiece/";
	private static final String D_CHEMIN_BLOCPIECE_IDPCE = "/Bordereau/Piece/BlocPiece/InfoPce/IdPce/";
	
	private static final String CHEMIN_PESPJ = "/PES_PJ/";
	private static final String CHEMIN_PJ = "/PES_PJ/PJ/";
	private static final String CHEMIN_PJ_IDPJ = "/PES_PJ/PJ/IdUnique/";
	
	
	
	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) {
		
		// RECETTE ou DEPENSE
		if (xpath.indexOf(DEPENSE)!=-1) {
			depense = true;
			CHEMIN_BLOCPIECE = D_CHEMIN_BLOCPIECE;
			CHEMIN_BLOCPIECE_IDPCE = D_CHEMIN_BLOCPIECE_IDPCE;
			
			
		}
		if (xpath.indexOf(RECETTE)!=-1) {
			depense = false;
			CHEMIN_BLOCPIECE = R_CHEMIN_BLOCPIECE;
			CHEMIN_BLOCPIECE_IDPCE = R_CHEMIN_BLOCPIECE_IDPCE;
			
		}
		
		if (xpath.endsWith(CHEMIN_PESPJ)) {
			PJ_nodeId = "";
		}
		
		if (xpath.endsWith(CHEMIN_PJ)) {
			PJ_idPJ = "";
			PJ_nodeId = atts.getValue("ano:node-id");
		}

		if (xpath.endsWith(CHEMIN_PJ_IDPJ)) {
			PJ_idPJ = atts.getValue("V");
			valeurs_id.add(PJ_idPJ);
			compteur++;
		}
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU)) {
			bord_Exer = bord_IdBord = bord_TypBord = "";
			bord_nodeId = atts.getValue("ano:node-id");
		}
		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_BLOCPIECE)) {
			piece_IdPce = "";
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_IDPCE)) {
			piece_IdPce = atts.getValue("V");
		}
	}
	

	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		boolean err = false;
		int i, j;
		
		if (xpath.endsWith(CHEMIN_PESPJ)){

			for (i=0; i<compteur; i++) {
				for (j=0; j<compteur; j++) {
					if (j!=i && valeurs_id.get(i).equals(valeurs_id.get(j)))
						err = true;
				}
			}
			
			if (err) {
				Vector<Anomalie> ano1 = new Vector<Anomalie>();
				
				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],
                                        (depense?BORDEREAU_DEPENSE:BORDEREAU_RECETTE), // élément importable
                                        bord_IdBord, // id élément importable
                                        localName,
                                        libelleLien,
                                        getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent(),
                                        getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
                                        getDocumentModel().getControlById(CTRL_ID).getSeverity(),
                                        path,
                                        xslParams);
				ano.addNode(new Node(PJ_nodeId));
				ano1.add(ano);
				return ano1;
			} else {
				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) {}
}
