/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2010 C ARIOUAT - assia.ariouat@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.dgfip.xemelios.controls.dpdirecte;

import java.util.Hashtable;
import java.util.Stack;
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;
/**
 * Implémente le contrôle N° M006
 * 
 * Si la zone AE TYPE_TIERS = 'ZCPD' alors la zone AE ID_CHORUS_TIERS doit être renseignée.
 */
public class  M006 extends AbstractUnitControl {
   private static final Logger logger = Logger.getLogger(M006.class);
   public static final String CTRL_ID = "CTL-M006" ;
   // pour stocker tous les paramètres d'execution des controles
   private Hashtable<String,Object> hParams; 
   // pour stocker les anomalies que l'on génère
   Vector<Anomalie> anomalies = null;
   // pour récupérer le texte des balises
   private Stack<StringBuffer> chars = new Stack<StringBuffer>();
   
   /**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */
   
       private String ENTETE_IDAE = "";
       private String entete_NodeId = "";
	   private boolean ID_CHORUS_TIERS_exist=false ;
	   private boolean IS_CONTRALABLE;
	   private String STRING_TO_COMPARE = "ZCPD";
	   private int compteur = 0;
	   private String ID_CHORUS_TIERS="";
	   private String ID_DP_DIRECTE_Unique = "";
		private String numLigneTexte = "";
	   
    
     /**
 	 * Variables devant être remplacées dans le message
 	 */
 	private static final String MSG_COMPTEUR = "#NOMBRE_DPDIRECTE#";
 	private static final String MSG_ENTETE_IDAE = "#ENTETE_IDAE#";
 	private static final String MSG_ERREUR = "#ERREUR#";
     
 	
     /**
 	 * Chemins vers les divers éléments que l'on veux lire
 	 */
    public static final transient String RESET_COUNTER_PATH = "FEN0029A/DP_DIRECTE/";
    public static final transient String REQUIRED_PATH = "FEN0029A/DP_DIRECTE/ENTETE/TYPE_TIERS/";
    public static final transient String ENTETE_PATH = "FEN0029A/DP_DIRECTE/ENTETE/";
    public static final transient String ID_CHORUS_TIERS_PATH = "FEN0029A/DP_DIRECTE/ENTETE/ID_CHORUS_TIERS/";
    public static final transient String ID_AE_PATH = "FEN0029A/DP_DIRECTE/ENTETE/ID_AE/";
    public static final transient String RETURN_ANOMALIES_PATH = RESET_COUNTER_PATH;


   public void endDocument() throws SAXException { }

   public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) throws SAXException {
    
	   if(xpath.equals(ENTETE_PATH )) {
		   entete_NodeId=atts.getValue("ano:node-id");
			if(atts.getValue("txt2xml:LineTxt")!=null){
				numLigneTexte = atts.getValue("txt2xml:LineTxt");
			} else {
				numLigneTexte = "";
			}
	   }	   
       if(xpath.equals(RESET_COUNTER_PATH)) {
           // on commence un nouveau DP_DIRECTE :
           // on remet ID_CHORUS_TIERS_exist,ID_FONCT_TIERS_exist,IS_CONTRALABLE à false
    	   ID_CHORUS_TIERS_exist=false ;
    	   IS_CONTRALABLE=false;
    	   //vider le vecteur d'anomalie
           anomalies = new Vector<Anomalie>();
           ENTETE_IDAE=null; 
           ID_CHORUS_TIERS="";
			ID_DP_DIRECTE_Unique = atts.getValue("ano:unique-id");

       }
    // A chaque nouvel élément, on vide la Stack
       chars.push(new StringBuffer());
   }
   
   public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
	   String erreur = "";
	    if(xpath.equals(REQUIRED_PATH)) {
		   // sur la fermeture  de TYPE_TIERS vérifier si la zone AE TYPE_TIERS = 'ZCPD'
	    	if(chars.peek().toString().equals(STRING_TO_COMPARE)){
			   IS_CONTRALABLE=true;
		   }
	   } else if(xpath.equals(ID_AE_PATH)) {
		   ENTETE_IDAE = chars.peek().toString();
		   compteur++;
	   } else if(IS_CONTRALABLE && xpath.equals(ID_CHORUS_TIERS_PATH)) {
		   ID_CHORUS_TIERS_exist = true;
		   ID_CHORUS_TIERS = chars.peek().toString();
	   }
	 
	    if (xpath.equals(RETURN_ANOMALIES_PATH)) {
		   if (IS_CONTRALABLE && ((ID_CHORUS_TIERS.equals(" ")) || (ID_CHORUS_TIERS.equals("")))){    
			   
				erreur = "Pour un type de tiers ZCPD, le champ ID_CHORUS_TIERS doit etre renseigne";
				String msg = (numLigneTexte.length()>0?"Ligne n°"+numLigneTexte+" : ":"");
				msg += getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
				msg = msg.replaceAll(MSG_COMPTEUR, String.valueOf(compteur));
				msg = msg.replaceAll(MSG_ENTETE_IDAE, ENTETE_IDAE);
				msg = msg.replaceAll(MSG_ERREUR, erreur);				
				
				String path = "@ano:unique-id='" + ID_DP_DIRECTE_Unique + "'";
				String anoId = IdGenerator.nextId();
				String libelleLien = "Entete "+ENTETE_IDAE;
				Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
				xslParams.put("anoId", anoId);
				xslParams.put("presentation", "src");
				Anomalie ano = new Anomalie(anoId,
	                                    getDocumentModel().getControlById(CTRL_ID).getId(),
	                                    getDocumentModel().getControlById(CTRL_ID).getLibelle(),
	                                    getDocumentModel().getDocumentId(),
	                                    "FEN0029A",
	                                    "DP_DIRECTE", // élément importable
	                                    ENTETE_IDAE, // id élément importable
	                                    localName,
	                                    libelleLien,
	                                    msg,
	                                    getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
	                                    getDocumentModel().getControlById(CTRL_ID).getSeverity(),
	                                    path,
	                                    xslParams);
				ano.addNode(new Node(entete_NodeId));
				anomalies.add(ano);	
		   }
		   chars.pop();		
		   return anomalies;
	    }	    
	   else {
		   chars.pop();
		   return null;
	   }
   }
	    
	    
   public void characters(char[] ch, int start, int length, String xpath) throws SAXException {
       //on stocke les caractères lus       
       chars.peek().append(ch, start, length);
   }

   public void ignorableWhitespace(char[] ch, int start, int length, String xpath) throws SAXException { }

   public void processingInstruction(String target, String data, String xpath) throws SAXException { }

   public void skippedEntity(String name, String xpath) throws SAXException { }

   public void setParameters(Hashtable<String, Object> params) {
       this.hParams=params;
   }

   public void setDocumentLocator(Locator locator) { }

   public void startDocument() throws SAXException {
	   logger.info("In "+CTRL_ID);
   }

   public void startPrefixMapping(String prefix, String uri, String xpath) throws SAXException { }

   public void endPrefixMapping(String prefix, String xpath) throws SAXException { }
}
