
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° M032
 * 
 * "RG02-02-FEN0058A : Le texte de l'élément EtatsFrais/Invoice/InvoiceTypeCode ne peut prendre que l'une des valeurs suivantes :
- K1 : DP du solde d'un état de frais
- K2 : DP de l'avance sur un état de frais
- K3 : DP de récupération d’avance sur état de f"



 */
public class M032 extends AbstractUnitControl {
	   private static final Logger logger = Logger.getLogger(M032.class);
	   public static final String CTRL_ID = "CTL-M032" ;
	   // 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_Unique = "";
	     private String ID_Invoice = "";
		 private String TYPECODE_NodeId="";
		 private String InvoiceTypeCode="";
		 private  Boolean InvoiceTypeCode_exist = false;
		 

     /**
 	 * Variables devant être remplacées dans le message
 	 */
	 	private static final String MSG_IDInvoice ="#ID_Invoice#";
	 	private static final String MSG_ERREUR = "#ERREUR#";
	 	private static final String MSG_TYPECODE= "#TYPECODE#";
	     
 	
     /**
 	 * Chemins vers les divers éléments que l'on veux lire
 	 */
	    public static final transient String CHEMIN_TYPECODE = "EtatsFrais/Invoice/InvoiceTypeCode/";
	    public static final transient String CHEMIN_INVOICE = "EtatsFrais/Invoice/";
	    public static final transient String CHEMIN_IDINVOICE = "EtatsFrais/Invoice/ID/";
	    public static final transient String RETURN_ANOMALIES_PATH = CHEMIN_INVOICE;


   public void endDocument() throws SAXException { }

   public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) throws SAXException {
    
	   if(xpath.equals(CHEMIN_INVOICE)) {
	           // on commence un nouveau Invoice :
	    	   //vider le vecteur d'anomalie
		   anomalies = new Vector<Anomalie>();
           ID_Invoice=""; 
           TYPECODE_NodeId=InvoiceTypeCode="";
           InvoiceTypeCode_exist=false;
           ID_Invoice_Unique = atts.getValue("ano:unique-id");
           }
	  
	   else if( xpath.equals(CHEMIN_TYPECODE)) {
		   TYPECODE_NodeId=atts.getValue("ano:node-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(CHEMIN_IDINVOICE)) {
		    	 ID_Invoice = chars.peek().toString();
		      } 
		     
		     else if( xpath.equals(CHEMIN_TYPECODE)) {
				   InvoiceTypeCode=chars.peek().toString();
				   InvoiceTypeCode_exist=true;
		   	   }	   
		 
	 
		     if (xpath.equals(RETURN_ANOMALIES_PATH)) {
		    	 if (!InvoiceTypeCode.equals("K1") && !InvoiceTypeCode.equals("K2") && !InvoiceTypeCode.equals("K3") && InvoiceTypeCode_exist){
					   
					erreur = "Le texte de l element EtatsFrais/Invoice/ID doit avoir une longueur de 12 caracteres maximum";
					String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
					msg = msg.replaceAll(MSG_IDInvoice, ID_Invoice);
					msg = msg.replaceAll(MSG_ERREUR, erreur);	
					msg = msg.replaceAll(MSG_TYPECODE, InvoiceTypeCode);	
					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);
					ano.addNode(new Node(TYPECODE_NodeId));
					anomalies.add(ano);
		             }
		   chars.pop();
           return anomalies;
       }
	    else{
       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 { }
	}
	
