/*
 * 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.tie;

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° TIE01
 * Il consiste à vérifier la règle fonctionnelle suivante :
 * 		A chaque ligne de pièce doit correspondre au moins un tiers.
 *		Les informations nécessaires sont les suivantes : 
 *		-	Le type d'adresse  (TypAdr doit être valorisé à 01 ou 02),
 *		-	Nom,
 *		-	Adresse (Adr2 est obligatoire, Adre1 et Adr3 sont facultatives), le code postal, la ville et le code pays (dans le cas d’une adresse à l’étranger),
 *		-	De plus s'il s’agit d’une personne physique, la civilité et le prénom doivent être obligatoirement indiqués,
 *		-	S’il s’agit d’une personne morale, la civilité et le prénom ne doivent pas être indiqués. 
 * Il est fait ainsi :
 * 		1- 	Lorsqu'on lit un élément BlocBordereau :
 * 			- on vide BlocBordereau/Exer/@V, BlocBordereau/IdBord/@V, BlocBordereau/Typbord/@V.
 * 			- on stocke BlocBordereau/Exer/@V, BlocBordereau/IdBord/@V, BlocBordereau/Typbord/@V. 
 * 		2- 	Lorsqu'on lit un élément BlocPiece :
 * 			- on vide BlocPiece/IdPce/@V, BlocPiece/TypPce/@V.
 * 			- on stocke BlocPiece/IdPce/@V, BlocPiece/TypPce/@V.
 * 		3- Lorsqu'on lit un élément InfoLignePiece :
 * 			- on valorise à false le booleen infoTiersExists et addresseExists.
 * 			- on vide InfoLignePiece/IdLigne/@V.
 * 			- on stocke InfoLignePiece/IdLigne/@V.
 * 		4- Lorsqu'on lit un élément InfoTiers/ :
 * 			- on valorise à vrai le booleen InfoTiersExists.
 * 			- on stocke InfoTiers/Nom/@V, InfoTiers/Prenom/@V, InfoTiers/Civilite/@V et InfoTiers/CatTiers/@V.
 * 		5- Lorsqu'on lit un élément Adresse/ :
 * 			- on valorise à vrai le booleen adresseExists.
 * 			- on stocke Adresse/TypAdr/@V, Adresse/Adr2/@V, Adresse/CP/@V et Adresse/Ville/@V.
 * 		6- Lorsqu'on lit une fin de LigneDePiece :
 * 			- Si domaine DEPENSE ou (RECETTE et TypPce vaut 06, 07 ou 14) :
 * 				- InfoTiers/ doit exister
 * 				- Adresse/TypAdr/@V vaut 1 ou 2
 * 				- InfoTiers/Nom/@V doit exister et ne pas valoir ""
 * 				- Adresse/ doit exister
 * 				- Adresse/Adr2/@V, Adresse/CP/@V et Adresse/Ville/@V sont obligatoires
 * 				- Si InfoTiers/CatTiers/@V = 01
 * 					InfoTiers/Prenom/@V, InfoTiers/Civilite/@V sont obligatoires
 *				  Sinon
 *					InfoTiers/Prenom/@V, InfoTiers/Civilite/@V ne doivent pas être renseignés
 */
public class TIE01 extends AbstractUnitControl implements ConstantsControlsPESv2 {
	private final static Logger logger = Logger.getLogger(TIE01.class);
    public static final transient String CTRL_ID = "TIE01";
	private Vector<Anomalie> anos = null;
	private Hashtable<String,Object> hParams;
	
	/**
	 * La balise du document général
	 */
	private String docId = null;
	private String ligne_nodeId = null;
	private String tiers_nodeId = null;
	
	/**
	 * La chaine cible
	 */
	private static final String ON_RETURN_ANOMALIES = "Piece";
	private static final String FIN_LIGNE_PIECE = "LigneDePiece";
	
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */
	private boolean depense = false;
	private String bord_Exer = "";
	private String bord_IdBord = "";
	private String bord_TypBord = "";
	private String piece_IdPce = "";
	private String piece_typPce = "";
	private String ligne_IdLigne = "";
	private String tiers_nom = "";
	private String tiers_prenom = "";
	private String tiers_civilite = "";
	private String tiers_catTiers = "";
	private String addr_typAdr = "";
	private String addr_adr2 = "";
	private String addr_CP = "";
	private String addr_ville = "";
	private boolean infoTiersExists = false;
	private boolean adresseExists = false;
	
	/**
	 * 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_PIECE_IDPCE = "#PIECE_IDPCE#";
	private static final String MSG_LIGNE_IDLIGNE = "#LIGNE_IDLIGNE#";
	
	/**
	 * 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 static final String CHEMIN_PIECE = "/Bordereau/Piece/";
	private static String CHEMIN_BLOCPIECE = "";
	private static String CHEMIN_BLOCPIECE_IDPCE = "";
	private static String CHEMIN_BLOCPIECE_TYPPCE = "";
	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 R_CHEMIN_BLOCPIECE_TYPPCE = "/Bordereau/Piece/BlocPiece/TypPce/";
	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 D_CHEMIN_BLOCPIECE_TYPPCE = "/Bordereau/Piece/BlocPiece/InfoPce/TypPce/";
	
	private static String CHEMIN_INFOLIGNEPIECE = "";
	private static String CHEMIN_INFOLIGNEPIECE_IDLIGNE = "";
	private static final String R_CHEMIN_INFOLIGNEPIECE = "/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/";
	private static final String R_CHEMIN_INFOLIGNEPIECE_IDLIGNE = "/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePiece/IdLigne/";
	private static final String D_CHEMIN_INFOLIGNEPIECE = "/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/";
	private static final String D_CHEMIN_INFOLIGNEPIECE_IDLIGNE = "/Bordereau/Piece/LigneDePiece/BlocLignePiece/InfoLignePce/IdLigne/";
	
	private static final String CHEMIN_INFOTIERS = "/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/";
	private static final String CHEMIN_INFOTIERS_NOM = "/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/Nom/";
	private static final String CHEMIN_INFOTIERS_PRENOM = "/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/Prenom/";
	private static final String CHEMIN_INFOTIERS_CIVILITE = "/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/Civilite/";
	private static final String CHEMIN_INFOTIERS_CATTIERS = "/Bordereau/Piece/LigneDePiece/Tiers/InfoTiers/CatTiers/";
	
	private static final String CHEMIN_ADRESSE = "/Bordereau/Piece/LigneDePiece/Tiers/Adresse/";
	private static final String CHEMIN_ADRESSE_TYPADR = "/Bordereau/Piece/LigneDePiece/Tiers/Adresse/TypAdr/";
	private static final String CHEMIN_ADRESSE_ADR2 = "/Bordereau/Piece/LigneDePiece/Tiers/Adresse/Adr2/";
	private static final String CHEMIN_ADRESSE_CP = "/Bordereau/Piece/LigneDePiece/Tiers/Adresse/CP/";
	private static final String CHEMIN_ADRESSE_VILLE = "/Bordereau/Piece/LigneDePiece/Tiers/Adresse/Ville/";
	
	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) {
		// 0
		// RECETTE ou DEPENSE
		if (xpath.indexOf(DEPENSE)!=-1) {
			depense = true;
			CHEMIN_BLOCPIECE = D_CHEMIN_BLOCPIECE;
			CHEMIN_BLOCPIECE_IDPCE = D_CHEMIN_BLOCPIECE_IDPCE;
			CHEMIN_BLOCPIECE_TYPPCE = D_CHEMIN_BLOCPIECE_TYPPCE;
			CHEMIN_INFOLIGNEPIECE = D_CHEMIN_INFOLIGNEPIECE;
			CHEMIN_INFOLIGNEPIECE_IDLIGNE = D_CHEMIN_INFOLIGNEPIECE_IDLIGNE;
		}
		if (xpath.indexOf(RECETTE)!=-1) {
			depense = false;
			CHEMIN_BLOCPIECE = R_CHEMIN_BLOCPIECE;
			CHEMIN_BLOCPIECE_IDPCE = R_CHEMIN_BLOCPIECE_IDPCE;
			CHEMIN_BLOCPIECE_TYPPCE = R_CHEMIN_BLOCPIECE_TYPPCE;
			CHEMIN_INFOLIGNEPIECE = R_CHEMIN_INFOLIGNEPIECE;
			CHEMIN_INFOLIGNEPIECE_IDLIGNE = R_CHEMIN_INFOLIGNEPIECE_IDLIGNE;
		}
		// 1
		if (xpath.endsWith(CHEMIN_BLOCBORDEREAU)) {
			bord_Exer = bord_IdBord = bord_TypBord = "";
		}
		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");
		}
		
		// 2
		if (xpath.endsWith(CHEMIN_BLOCPIECE)) {
			piece_IdPce = ligne_nodeId = "";
			anos = new Vector<Anomalie>();
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_IDPCE)) {
			piece_IdPce = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_BLOCPIECE_TYPPCE)) {
			piece_typPce = atts.getValue("V");
		}
		
		// 3
		if (xpath.endsWith(CHEMIN_INFOLIGNEPIECE)) {
			ligne_IdLigne = "";
			ligne_nodeId = atts.getValue("ano:node-id");
			tiers_nodeId = null;
			infoTiersExists = adresseExists = false;
		}
		if (xpath.endsWith(CHEMIN_INFOLIGNEPIECE_IDLIGNE)) {
			ligne_IdLigne = atts.getValue("V");
		}
		
		// 4
		if (xpath.endsWith(CHEMIN_INFOTIERS)) {
			infoTiersExists = true;
			tiers_nom = tiers_prenom = tiers_civilite = tiers_catTiers = "";
			tiers_nodeId = atts.getValue("ano:node-id");
		}
		if (xpath.endsWith(CHEMIN_INFOTIERS_NOM)) {
			tiers_nom = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_INFOTIERS_PRENOM)) {
			tiers_prenom = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_INFOTIERS_CIVILITE)) {
			tiers_civilite = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_INFOTIERS_CATTIERS)) {
			tiers_catTiers = atts.getValue("V");
		}
		
		// 5
		if (xpath.endsWith(CHEMIN_ADRESSE)) {
			adresseExists = true;
			addr_typAdr = addr_adr2 = addr_CP = addr_ville = "";
		}
		if (xpath.endsWith(CHEMIN_ADRESSE_TYPADR)) {
			addr_typAdr = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_ADRESSE_ADR2)) {
			addr_adr2 = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_ADRESSE_CP)) {
			addr_CP = atts.getValue("V");
		}
		if (xpath.endsWith(CHEMIN_ADRESSE_VILLE)) {
			addr_ville = atts.getValue("V");
		}
	}
	

	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if(ON_RETURN_ANOMALIES.equals(localName)){
			return anos;
		// 6
		} else if (FIN_LIGNE_PIECE.equals(localName)) {
			boolean err = false;
			if (depense || (!depense && (!"06".equals(piece_typPce)&&!"07".equals(piece_typPce)&&!"14".equals(piece_typPce)))) {
				if (!infoTiersExists) {
					err = true;
				} else if (!"1".equals(addr_typAdr) && !"2".equals(addr_typAdr)) {
					err = true;
				} else if ("".equals(tiers_nom)) {
					err = true;
				} else if (!adresseExists) {
					err = true;
				} else if ("".equals(addr_adr2) || "".equals(addr_CP) || "".equals(addr_ville)) {
					err = true;
				} else if ("01".equals(tiers_catTiers) && ("".equals(tiers_prenom) || "".equals(tiers_civilite))) {
					err = true;
				} else if (!"01".equals(tiers_catTiers) && (!"".equals(tiers_prenom) || !"".equals(tiers_civilite))) {
					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_TYPBORD, bord_TypBord);
				msg = msg.replaceAll(MSG_PIECE_IDPCE, piece_IdPce);
				msg = msg.replaceAll(MSG_LIGNE_IDLIGNE, ligne_IdLigne);
				if (depense) {
					msg = msg.replaceAll("#MT#", "Mandat");
				} else {
					msg = msg.replaceAll("#MT#", "Titre");
				}
				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,
                                        msg,
                                        getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
                                        getDocumentModel().getControlById(CTRL_ID).getSeverity(),
                                        path,
                                        xslParams);
				ano.addNode(new Node((tiers_nodeId!=null?tiers_nodeId:ligne_nodeId)));
				anos.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) {}
}
