/*
 * 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° M200
 * 
 * Si les zones AE ASSET_NO et SUB_NUMBER sont renseignées (DP sur immobilisation) alors la zone AE CODE_MVT_IMMO doit être renseignée.
 */
public class  M200 extends AbstractUnitControl {
   private static final Logger logger = Logger.getLogger(M200.class);
   public static final String CTRL_ID = "CTL-M200" ;
   // 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 int compteur = 0;
	   private String ASSET_NO="";
	   private String SUB_NUMBER="";
	   private String CODE_MVT_IMMO="";
	   private String ID_DP_DIRECTE_Unique = "";
	   private String numLigneTexte = "";
	   private String LIGNE_CHARGE_ID = "";
	   private String NUM_LIGNE = "";

	   
     /**
 	 * 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_NUM_LIGNE= "#NUM_LIGNE#";
 	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 NUM_LIGNE_PATH = "FEN0029A/DP_DIRECTE/LIGNE_CHARGE/NUM_LIGNE/";
    public static final transient String ENTETE_PATH = "FEN0029A/DP_DIRECTE/ENTETE/";
    public static final transient String ASSET_NO_PATH ="FEN0029A/DP_DIRECTE/LIGNE_CHARGE/ASSET_NO/";
    public static final transient String SUB_NUMBER_PATH ="FEN0029A/DP_DIRECTE/LIGNE_CHARGE/SUB_NUMBER/";
    public static final transient String CODE_MVT_IMMO_PATH ="FEN0029A/DP_DIRECTE/LIGNE_CHARGE/CODE_MVT_IMMO/";
    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(RESET_COUNTER_PATH)) {           
	            anomalies = new Vector<Anomalie>();	                     
	            ID_DP_DIRECTE_Unique = atts.getValue("ano:unique-id");   
	            ID_Dpdirecte="";  
	            compteur++;
		   
		   }
	        	 
	       if (xpath.equals(LIGNE_CHARGE_PATH)){
	    	     ASSET_NO="";
	     	     SUB_NUMBER="";
	     	     CODE_MVT_IMMO="";
	     	     LIGNE_CHARGE_ID="";
	     	     LIGNE_CHARGE_ID = atts.getValue("ano:node-id");}

	       if(atts.getValue("txt2xml:LineTxt")!=null){
				numLigneTexte = atts.getValue("txt2xml:LineTxt");
			} else {
				numLigneTexte = "";
			}
	        
	        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(NUM_LIGNE_PATH)) 
	   {   
		   NUM_LIGNE= chars.peek().toString();
	   }
	   if(xpath.equals(ASSET_NO_PATH)) {
		  
	    	ASSET_NO=chars.peek().toString();
	   } 
	    else if(xpath.equals(SUB_NUMBER_PATH)) {
	    	SUB_NUMBER=chars.peek().toString();
	    }
	    else if(xpath.equals(CODE_MVT_IMMO_PATH)) {
	    	CODE_MVT_IMMO=chars.peek().toString();
	    }
	 
	    if (xpath.equals(LIGNE_CHARGE_PATH)) {
		   if (ASSET_NO.length()!=0 && SUB_NUMBER.length()!=0 )
			   if (CODE_MVT_IMMO.length()==0  )
		   {    
			   
				erreur = "Pour une DP sur immobilisation le code mouvement immobilisation est obligatoire";
				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_NUM_LIGNE, NUM_LIGNE);
				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(LIGNE_CHARGE_ID));
				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 { }
}
