/*
 * Copyright 
 *   2008 axYus - www.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.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° REC29
 * 
 * Il consiste à vérifier la règle fonctionnelle suivante :
 * La référence à la pièce initiale doit être alimentée dans le cas des charges à répartir, des produits constatés d'avance et des produits à rattacher.
 * 
 */


public class REC29 extends AbstractUnitControl implements ConstantsControlsPESv2{
	private final static Logger logger = Logger.getLogger(REC29.class);
	public static final transient String CTRL_ID = "REC29";
	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_PIECE = "/PES_RecetteAller/Bordereau/Piece/";
	private static final String LIGNEPCE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/";
	private static final String ON_RETURN_ANOMALIES = FIN_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 piece_TypPce = "";	
	private String piece_NatPce = "";	
	private String ligne_IdLigne = "";
	private String ligne_Nature = "";
	private String rattachPiece_NatPceOrig = "";
	private String rattachPiece_ExerRat = "";
	
	
	private String ligne_IdLigne_NodeId = "";
	private String rattachPiece_NatPceOrig_nodeId = "";
	private String rattachPiece_ExerRat_nodeId = "";

	private boolean rattachPiece_exist = false;
	

	
	/**
	 * Variables devant être remplacées dans le message-echec
	 */
	
	private static final String MSG_BORD_NUM = "#BORD_NUM#";
	private static final String MSG_PIECE_ID = "#PIECE_IDPCE#";
	private static final String MSG_LIGNE_IDLIGNE = "#LIGNE_IDLIGNE#";
	private static final String MSG_ERREUR = "#ERREUR#";
	
	/**
	 * 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_PIECE = "/PES_RecetteAller/Bordereau/Piece/";
	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_BLOCPIECE_NATPIECE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/NatPce/";
	private static final String CHEMIN_BLOCPIECE_IDPIECE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/IdPce/";
	private static final String CHEMIN_BLOCPIECE_TYPPIECE = "/PES_RecetteAller/Bordereau/Piece/BlocPiece/TypPce/";
	private static final String CHEMIN_BLOCLIGNEPIECE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/";
	private static final String CHEMIN_BLOCLIGNEPIECE_RATTACHPIECE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/RattachPiece/";
	private static final String CHEMIN_RATTACHPIECE_NATPCEORIG = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/RattachPiece/NatPceOrig/";
	private static final String CHEMIN_RATTACHPIECE_EXERRAT = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/RattachPiece/ExerRat/";
	private static final String CHEMIN_INFOLIGNEPIECE_IDLIGNE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/IdLigne/";
	private static final String CHEMIN_INFOLIGNEPIECE_NATURE = "/PES_RecetteAller/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/Nature/";

	
	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) {
		
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU)) {
			bord_ExerBord = bord_IdBord = bord_TypBord = "";
		}
		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_PIECE)) {
			if (anos != null)
				anos = new Vector<Anomalie>();			
			piece_IdPce = piece_TypPce = piece_NatPce = "";			
		}		
		if(xpath.endsWith(CHEMIN_BLOCPIECE_IDPIECE)){
			piece_IdPce = atts.getValue("V");
			anos.clear();
		}
		if(xpath.endsWith(CHEMIN_BLOCPIECE_TYPPIECE)){
			piece_TypPce = atts.getValue("V");
		}
		if(xpath.endsWith(CHEMIN_BLOCPIECE_NATPIECE)){
			piece_NatPce = atts.getValue("V");
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE)){
			ligne_IdLigne = ligne_Nature = "";
			ligne_IdLigne_NodeId = "";	
			rattachPiece_exist = false;
			rattachPiece_ExerRat = rattachPiece_NatPceOrig = "";
			rattachPiece_ExerRat_nodeId = rattachPiece_NatPceOrig_nodeId = "";
		}
		if(xpath.endsWith(CHEMIN_BLOCLIGNEPIECE_RATTACHPIECE)){
			rattachPiece_exist = true;
		}
		if(xpath.endsWith(CHEMIN_RATTACHPIECE_NATPCEORIG)){
			rattachPiece_NatPceOrig = atts.getValue("V");
			rattachPiece_NatPceOrig_nodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_RATTACHPIECE_EXERRAT)){
			rattachPiece_ExerRat = atts.getValue("V");
			rattachPiece_ExerRat_nodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_INFOLIGNEPIECE_IDLIGNE)){
			ligne_IdLigne = atts.getValue("V");
			ligne_IdLigne_NodeId = atts.getValue("ano:node-id");
		}
		if(xpath.endsWith(CHEMIN_INFOLIGNEPIECE_NATURE)){
			ligne_Nature = atts.getValue("V");
		}
		
	}


	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		Vector<Node> anonodes = new Vector<Node>();
		boolean err = false;
		String erreur = "";
		
		if(xpath.endsWith(LIGNEPCE)){
			
				if ( haveToTest() ){
					
					 if ( ((piece_TypPce.equals("03") && piece_NatPce.equals("01") && ligne_Nature.startsWith("79")) || (piece_TypPce.equals("03") && piece_NatPce.equals("02") && ligne_Nature.startsWith("481"))) && 																		
						( !rattachPiece_exist || !rattachPiece_NatPceOrig.equals("02") || ( Integer.parseInt(bord_ExerBord) != Integer.parseInt(rattachPiece_ExerRat) ) )){
					
						 	err = true;
						 	
							if (!rattachPiece_exist){
								anonodes.add(new Node (ligne_IdLigne_NodeId));
								erreur = "La pièce initiale n'est pas renseignée";
							}
							else {
								if (!rattachPiece_NatPceOrig.equals("02")){					
									anonodes.add(new Node (rattachPiece_NatPceOrig_nodeId));
								}
								if (Integer.parseInt(bord_ExerBord) != Integer.parseInt(rattachPiece_ExerRat)){
									anonodes.add(new Node (rattachPiece_ExerRat_nodeId));			
								}
								erreur = "L'exercice de la pièce de rattachement doit être égal à l'exercice du bordereau";
							}							
					 }	
					 
					 if ( ((piece_TypPce.equals("14") && piece_NatPce.equals("01")) || (piece_TypPce.equals("02") && piece_NatPce.equals("10"))) && 																		
								( !rattachPiece_exist || !rattachPiece_NatPceOrig.equals("01") || ((Integer.parseInt(bord_ExerBord)-1) != Integer.parseInt(rattachPiece_ExerRat)) )){
							
								 	err = true;
								 	
									if (!rattachPiece_exist){
										anonodes.add(new Node (ligne_IdLigne_NodeId));
										erreur = "La pièce initiale n'est pas renseignée";
									}
									else {
										if (!rattachPiece_NatPceOrig.equals("01")){					
											anonodes.add(new Node (rattachPiece_NatPceOrig_nodeId));
										}
										if ((Integer.parseInt(bord_ExerBord)-1) != Integer.parseInt(rattachPiece_ExerRat)){
											anonodes.add(new Node (rattachPiece_ExerRat_nodeId));			
										}
										erreur = "L'exercice de la pièce de rattachement doit être égal à l'exercice du bordereau";
									}							
							 }					 				 
				}
					 
					 					 
			if (err){	
				
					String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
					msg = msg.replaceAll(MSG_BORD_NUM, bord_IdBord);
					msg = msg.replaceAll(MSG_PIECE_ID, piece_IdPce);
					msg = msg.replaceAll(MSG_LIGNE_IDLIGNE, ligne_IdLigne);
					msg = msg.replaceAll(MSG_ERREUR, erreur);	
					String path="@added:primary-key='"+bord_ExerBord+"-"+bord_TypBord+"-"+bord_IdBord+"'";
					String anoId = IdGenerator.nextId();
					String libelleLien = "Bordereau "+bord_IdBord+" Titre "+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().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);
					anos.add(ano);
				
			}
			
			return null;		
		}
		else if (xpath.endsWith(ON_RETURN_ANOMALIES)){
						
			return anos;
			
		} else {
			return null;
		}
	}
	
	
	
	public boolean haveToTest(){
		String PAR1 = (String)hParams.get("nomencl");
		return (PAR1.equals("M4") || PAR1.equals("M14") || PAR1.equals("M52") || PAR1.equals("M61") || PAR1.equals("M71"));
	}
	
	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) {}
	
}
