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

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 ID_AMG commence par CRG alors CODE_PAYS_OSD est obligatoire
 *
 * @author Assia ARIOUAT
 */

public class M207 extends AbstractUnitControl {
    public static final String CTRL_ID = "CTL-M207" ;
    public static final transient String RESET_COUNTER_PATH = "FEN0052A/FACTURE/";
    public static final transient String ENTETE_PATH = "FEN0052A/FACTURE/ENTETE/";
    public static final transient String NUM_FACT_PATH = "FEN0052A/FACTURE/ENTETE/NUM_FACT/";
    public static final transient String ENTETE_ID_AMG= "FEN0052A/FACTURE/ENTETE/ID_AMG/";
    public static final transient String ENTETE_CODE_PAYS_OSD= "FEN0052A/FACTURE/ENTETE/CODE_PAYS_OSD/";
    public static final transient String RETURN_ANOMALIES_PATH = RESET_COUNTER_PATH;
    
    private static final Logger logger = Logger.getLogger(M207.class);

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

    // pour stocker l'identifiant de l'invoice, on en a besoin pour générer l'anomalie
    private String numfact = "";
	private String ID_Facture_Unique = "";
    private String id_amg = "";
    private String code_pays_osd = "";
    private String numLigneTexte = "";
    private String entete_Nod="";
    
    //Varriables du message d'erreur
    
	private static final String MSG_ENTETE_IDFACTURE = "#ENTETE_IDFACTURE#";
	private static final String MSG_POSTE_ID = "#POSTE_ID#";
	
    
    // 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)) {    
    		entete_Nod= atts.getValue("ano:node-id");
    	}
    	if(xpath.equals(RESET_COUNTER_PATH)) {           
            anomalies = new Vector<Anomalie>();
            numfact =code_pays_osd= id_amg="";   
            ID_Facture_Unique = atts.getValue("ano:unique-id");
        } 
        else 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 {
        if(xpath.equals(NUM_FACT_PATH)) {
        	numfact = chars.peek().toString();
        } else if(xpath.equals(ENTETE_ID_AMG)) {   
        	id_amg = chars.peek().toString();
        } else if(xpath.equals(ENTETE_CODE_PAYS_OSD)) {   
        	code_pays_osd = chars.peek().toString();
        } else if(xpath.equals(ENTETE_PATH)) {   
        
        	if ( id_amg.startsWith("CRG")&&(code_pays_osd.length()==0)) {
        		String msg = (numLigneTexte.length()>0?"Ligne n°"+numLigneTexte+" : ":"");
    			msg += getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
    			msg = msg.replaceAll(MSG_ENTETE_IDFACTURE, numfact);
    			String path = "@ano:unique-id='" + ID_Facture_Unique + "'";
    			String anoId = IdGenerator.nextId();
    			String libelleLien = "Entete "+numfact;
    			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(),
                                        "FEN0052A",
                                        "FACTURE", // élément importable
                                        numfact, // id élément importable
                                        localName,
                                        libelleLien,
                                        msg,
                                        getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
                                        getDocumentModel().getControlById(CTRL_ID).getSeverity(),
                                        path,
                                        xslParams);
                    ano.addNode(new Node(entete_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 { }

    public void startPrefixMapping(String prefix, String uri, String xpath) throws SAXException { }

    public void endPrefixMapping(String prefix, String xpath) throws SAXException { }
}
