
package fr.gouv.finances.dgfip.xemelios.controls.entreesdirectesstock;

/*
 * Copyright 
 *   2010 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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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
 */


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;

/**
 * Si CODE_MVT = ‘501’, TXT_ENTETE et VAL sont valorisés
 * @author Assia ARIOUAT
 */
public class M169 extends AbstractUnitControl {
    public static final String CTRL_ID = "CTL-M169" ;
    public static final transient String RESET_COUNTER_PATH = "FEN0070A/EDS/";
    public static final transient String CHEMIN_ENTETE = "FEN0070A/EDS/ENTETE/";
    public static final transient String CHEMIN_ENTETE_IDAE = "FEN0070A/EDS/ENTETE/ID_AE/";
    public static final transient String CHEMIN_TXT_ENTETE= "FEN0070A/EDS/ENTETE/TXT_ENTETE/";
    public static final transient String CHEMIN_CODE_MVT= "FEN0070A/EDS/ENTETE/CODE_MVT/";
    public static final transient String CHEMIN_VAL= "FEN0070A/EDS/POSTE/VAL/";
    public static final transient String CHEMIN_IDPOSTE = "FEN0070A/EDS/POSTE/ID_AE/";
    public static final transient String CHEMIN_POSTE = "FEN0070A/EDS/POSTE/";
    public static final transient String CHEMIN_ID_LIG= "FEN0070A/EDS/POSTE/ID_LIG/";

    public static final transient String RETURN_ANOMALIES_PATH = RESET_COUNTER_PATH;

    private static final Logger logger = Logger.getLogger(M169.class);

    // pour stocker tous les paramètres d'execution des controles
    private Hashtable<String,Object> hParams;

    private String ID_EDS = null;
	private String ID_EDS_Unique = "";
    private String  val = "";
    private String txt_entete = "";
    private String idIPOSTE = "";
	private String numLigneTexte = "";
	private String val_Nod = "";
	private String text_Nod = "";	
	private String id_lig = "";
	private String cod_mvt = "";
	private String 	cod_mvt_Nod = "";

    //pour le message d'erreurs
    private static final String MSG_IDPOSTE= "#IDPOSTE#";
    private static final String MSG_ID_LIG = "#ID_LIG#";
       
    // 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(CHEMIN_TXT_ENTETE)){
    		text_Nod = atts.getValue("ano:node-id");
    	}
    	
    	if(xpath.equals(CHEMIN_CODE_MVT)){
        	cod_mvt_Nod = atts.getValue("ano:node-id");
        	}
    	
    	if(xpath.equals(CHEMIN_VAL)){
        	val_Nod = atts.getValue("ano:node-id");
        	}
    	if(xpath.equals(RESET_COUNTER_PATH)) {           
            anomalies = new Vector<Anomalie>();
            ID_EDS =txt_entete=cod_mvt= "";            
            ID_EDS_Unique = atts.getValue("ano:unique-id");  
           
        } else if(xpath.equals(CHEMIN_POSTE)) {
        	val ="";  
        	idIPOSTE=id_lig="";
        	}
        	       
        chars.push(new StringBuffer());
    }

    public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
    	
    		if(xpath.equals(CHEMIN_ENTETE_IDAE)) {
    			ID_EDS = chars.peek().toString();
    			}
    		else if (xpath.equals(CHEMIN_IDPOSTE)){
    			idIPOSTE=chars.peek().toString();
    			}
    		else if(xpath.equals(CHEMIN_ID_LIG)) {
    			id_lig = chars.peek().toString();
			}
    		 else if(xpath.equals(CHEMIN_VAL)) {
    			 
    			 val=chars.peek().toString();
    			 }
    		
    		 else if(xpath.equals(CHEMIN_CODE_MVT)){
    			 cod_mvt= chars.peek().toString();

    		      }
    		 else if(xpath.equals(CHEMIN_TXT_ENTETE)){
    			 txt_entete= chars.peek().toString();

    		      }
    		 else if(xpath.equals(CHEMIN_POSTE)){
	          
    		  if (cod_mvt.equals("501")){
    		      if((val.length()==0)||(txt_entete.length()==0)){       	
        	
	        			String anoId = IdGenerator.nextId();
	                    Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
	                    xslParams.put("anoId", anoId);
	                    xslParams.put("presentation","src");
	                    String libelleLien = "EDS_ID "+ID_EDS;
	                    String path = "@ano:unique-id='" + ID_EDS_Unique + "'";
	                    // on reconstitue le message
	                    String msg = (numLigneTexte.length()>0?"Ligne n°"+numLigneTexte+" : ":"");
	        			msg += getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
	        			msg = msg.replace("#EDS_ID#", ID_EDS);
	                    msg = msg.replaceAll(MSG_IDPOSTE, idIPOSTE);
	                    msg = msg.replaceAll(MSG_ID_LIG, id_lig);
	                          
	                    Anomalie ano = new Anomalie(anoId,
	                            getDocumentModel().getControlById(CTRL_ID),
	                            getDocumentModel().getDocumentId(),
	                            "FEN0070A",
	                            "EDS",
	                            ID_EDS,
	                            localName,  // l'élément en anomalie est bien EDS
	                            libelleLien,
	                            msg,
	                            getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
	                            getDocumentModel().getControlById(CTRL_ID).getSeverity(),
	                            path,
	                            xslParams);
	                    
	                    ano.addNode(new Node(cod_mvt_Nod));
	                    ano.addNode(new Node(val_Nod));
	                    ano.addNode(new Node(text_Nod));
	                    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 met les caractères lus dans la pile
        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 { }
}
