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

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° M033
 * 
 *  Vérifier que le texte l'élément EtatsFrais/Invoice/UBLExtensions/UBLExtension/ExtensionContent/EtatFraisExtension/EtatFrais/Valideur/PartyIdentification/ID a une longueur de 12 caractères maximum


 */
public class M033 extends AbstractUnitControl {
	   private static final Logger logger = Logger.getLogger(M033.class);
	   public static final String CTRL_ID = "CTL-M033" ;
	   // 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 ID_Invoice = "";
       private String ID_PartyIdentification_NodeId="";
       private Vector<String> vecteur_nodeId = new Vector<String>();
       boolean anomalie = false;
	   private String ID_Invoice_Unique = "";
	   private String ID_PartyIdentification = "";

	   
    
     /**
 	 * Variables devant être remplacées dans le message
 	 */
	 	private static final String MSG_ID_PartyIdentification ="#ID_PartyIdentification#";
	 	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 = "EtatsFrais/Invoice/";
	    public static final transient String REQUIRED_PATH = "EtatsFrais/Invoice/UBLExtensions/UBLExtension/ExtensionContent/EtatFraisExtension/EtatFrais/Valideur/PartyIdentification/ID/";
	    public static final transient String UBLExtension_PATH = "EtatsFrais/Invoice/UBLExtensions/UBLExtension/";
	    public static final transient String ID_Invoice_PATH ="EtatsFrais/Invoice/ID/";
	    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(UBLExtension_PATH )){		   
		   ID_PartyIdentification_NodeId="";
	   }
	   if(xpath.equals(REQUIRED_PATH )) {
		    ID_PartyIdentification_NodeId=atts.getValue("ano:node-id");   
	     }	   
       if(xpath.equals(RESET_COUNTER_PATH)) {
	           // on commence un nouveau Invoice :
	    	   //vider le vecteur d'anomalie
	           anomalies = new Vector<Anomalie>();
	           ID_Invoice="";
	           anomalie=false;
	           vecteur_nodeId.clear();
	           ID_Invoice_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)) {
			if ((chars.peek().toString().length()>12)||(chars.peek().toString().length()==0)){
				anomalie=true;
				vecteur_nodeId.add(ID_PartyIdentification_NodeId);
				ID_PartyIdentification = chars.peek().toString();
			 }
	     }  
		
		if(xpath.equals(ID_Invoice_PATH)) {
			   ID_Invoice = chars.peek().toString();
		} 

	     if (anomalie && (xpath.equals(RETURN_ANOMALIES_PATH))){  
			   
				erreur = "Longueur du texte de l'élément   .../EtatFrais/Valideur/PartyIdentification/ID doit etre de 12 car. maxi.";

				String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
				msg = msg.replaceAll(MSG_ID_PartyIdentification, ID_PartyIdentification);
				msg = msg.replaceAll(MSG_ERREUR, erreur);				
				String path = "@ano:unique-id='" + ID_Invoice_Unique + "'";
                String anoId = IdGenerator.nextId();
				String libelleLien = "Invoice "+ID_Invoice;
				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),
				                        getDocumentModel().getDocumentId(),
	                                    "EtatFrais",
	                                    "invoice",
	                                    ID_Invoice,
	                                    localName,
	                                    libelleLien,
	                                    msg,
	                                    getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
	                                    getDocumentModel().getControlById(CTRL_ID).getSeverity(),
	                                    path,
	                                    xslParams);
				for (int i=0; i<vecteur_nodeId.size(); i++)
					ano.addNode(new Node(vecteur_nodeId.get(i)));
				anomalies.add(ano);
					     
		    	chars.pop();
		        return anomalies;
	     }
			
          chars.pop();
		  return null;		  
   }
		   
          

   private void Println(String partyIdentification) {
	// TODO Auto-generated method stub
	
}
		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 { }
	}

