/*
 * 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° M204
 * 
 *Si l’application émettrice est ‘CRG’ (COREGE) (« Code_appli »commence par ‘CRG’) :
•	Si PYMT_METH (mode de paiement) = ‘A’ alors la zone AE PAYMT_REF  est obligatoire et les valeurs autorisées sont ‘VB’, ‘CF’ et ‘CP’
•	Si PYMT_METH = ‘E’ alors la zone AE PAYMT_REF  est obligatoire et les valeurs autorisées sont ‘VB’ et ‘CH’
•	Si PYMT_METH <> ‘A’ et ‘E’ alors la zone AE PAYMT_REF  est facultative et les valeurs autorisées sont ‘VB’, ‘CF’, ‘CP’ et ‘CH’.
 */
public class  M204 extends AbstractUnitControl {
   private static final Logger logger = Logger.getLogger(M202.class);
   public static final String CTRL_ID = "CTL-M204" ;
   // pour stocker tous les paramètres d'execution des controles
   private Hashtable<String,Object> hParams; 
   
   /**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */
   
       private String ID_Dpdirecte = "";
       private String ID_AEntete = "";
	   private int compteur = 0;
	   private String PYMT_METH="";
	   private String PAYMT_REF="";
	   private String CODE_APPLI="";
	   private String ID_DP_DIRECTE_Unique = "";
	   private String numLigneTexte = "";
	   private String PYMT_METH_AE="";
       private boolean PAYMT_REF_Exist = false;
     
	  /**
 	 * 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_PYMT_METH = "#MSG_PYMT_METH#";
 	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 LIGNE_CHARGE_PATH = "FEN0029A/DP_DIRECTE/LIGNE_CHARGE/";
    public static final transient String LIGNE_CHARGE_ID_PATH = "FEN0029A/DP_DIRECTE/LIGNE_CHARGE/ID_AE/";
    public static final transient String ENTETE_ID_AE = "FEN0029A/DP_DIRECTE/ENTETE/ID_AE/";
    public static final transient String ENTETE_PATH = "FEN0029A/DP_DIRECTE/ENTETE/";
    public static final transient String PYMT_METH_PATH ="FEN0029A/DP_DIRECTE/ENTETE/PYMT_METH/";
    public static final transient String PAYMT_REF_PATH ="FEN0029A/DP_DIRECTE/ENTETE/PAYMT_REF/";
    public static final transient String CODE_APPLI_PATH ="FEN0029A/DP_DIRECTE/ENTETE/CODE_APPLI/";
    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;

 // pour récupérer le texte des balises
    private Stack<StringBuffer> chars = new Stack<StringBuffer>();

    // pour stocker les anomalies que l'on génère
    Vector<Anomalie> anomalies = null;

    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)){
			   ID_AEntete = atts.getValue("ano:node-id");
		   }

		   if(xpath.equals(ENTETE_PATH))
	        {
           
           if(atts.getValue("txt2xml:LineTxt")!=null){
				numLigneTexte = atts.getValue("txt2xml:LineTxt");
			} else {
				numLigneTexte = "";
			}
           }
		   if(xpath.equals(RESET_COUNTER_PATH)) 
		   {           
	            anomalies = new Vector<Anomalie>();	                     
	            ID_DP_DIRECTE_Unique = atts.getValue("ano:unique-id");   
	            ID_Dpdirecte="";  
	            compteur++;
	            PYMT_METH_AE="";
	            PYMT_METH="";
	            PAYMT_REF="";
		        CODE_APPLI="";
		        PAYMT_REF_Exist=false; 
		     }

	        chars.push(new StringBuffer());
	           }

   public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
	   String erreur = "";
	
	   if(xpath.equals(ENTETE_ID_AE)) 
	   {   
	     ID_Dpdirecte=  chars.peek().toString();
	    }

	   if(xpath.equals(PYMT_METH_PATH)) {
		  
		   PYMT_METH=chars.peek().toString();
	   } 
	    else if(xpath.equals(PAYMT_REF_PATH)) {
	    	PAYMT_REF=chars.peek().toString();
	    	if (PAYMT_REF.length()!=0)
	    	   {
	    		PAYMT_REF_Exist= true;
	    	   }	
	    }
	    else if(xpath.equals(CODE_APPLI_PATH)) {
	    	CODE_APPLI=chars.peek().toString();
	          }
	 
	    if (xpath.equals(ENTETE_PATH)) {
		   if (CODE_APPLI.startsWith("CRG")) {
				   
			  if (((PYMT_METH.equals("A"))&& (!PAYMT_REF.equals("VB")) && (!PAYMT_REF.equals("CP" ))&& (!PAYMT_REF.equals("CF"))) || 
					  
					  ((PYMT_METH.equals("E"))&& (!PAYMT_REF.equals("VB")) && (!PAYMT_REF.equals("CH" ))) ||
					  
					  ((!PYMT_METH.equals("A"))&& (!PYMT_METH.equals("E"))&&  (PAYMT_REF_Exist)&&(!PAYMT_REF.equals("CP")) && (!PAYMT_REF.equals("CH" ))&& (!PAYMT_REF.equals("CF" ))&& (!PAYMT_REF.equals("CH" ))))

							  {    
				erreur = "Les valeurs autorisées de la zone PAYMT_REF ne sont pas respectées.";
				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, ID_Dpdirecte);
				msg = msg.replaceAll(MSG_PYMT_METH, PYMT_METH);
				msg = msg.replaceAll(MSG_ERREUR, erreur);				
				
				String path = "@ano:unique-id='" + ID_DP_DIRECTE_Unique + "'";
				String anoId = IdGenerator.nextId();
				String libelleLien = "Entete "+ID_Dpdirecte;
				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
	                                    ID_Dpdirecte, // id élément importable
	                                    localName,
	                                    libelleLien,
	                                    msg,
	                                    getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
	                                    getDocumentModel().getControlById(CTRL_ID).getSeverity(),
	                                    path,
	                                    xslParams);
				ano.addNode(new Node(ID_AEntete));
				anomalies.add(ano);							
		   }
		   chars.pop();	
		   return null;
		   }}
	     else if(xpath.equals(RETURN_ANOMALIES_PATH)){
        	chars.pop();
            return anomalies;
        }
        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 { }
}


