/*
 * 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.sortiesdirectesstock;
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° M108 
 * Les valeurs autorisées sont pour CODE_MVT sont
• en entrée: ‘501’, ‘521’ ou ‘701’
• en sortie : ‘201’,’551’ ou ‘702’

 */

public class M108 extends AbstractUnitControl {
	
	private final static Logger logger = Logger.getLogger(M108.class);
    public static final transient String CTRL_ID = "CTL-M108";
	private Hashtable<String,Object> hParams;
	Vector<Anomalie> anomalies = new Vector<Anomalie>();
	
	/**
	 * Variables devant être remplacées dans le message
	 */
	private static final String MSG_COMPTEUR = "#NOMBRE_EDS#";
	private static final String MSG_ENTETE_IDAE = "#ENTETE_IDAE#";
	private static final String MSG_ENTETE_CODE_MVT = "#ENTETE_CODE_MVT#";
	private static final String MSG_ERREUR = "#ERREUR#";
	
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */

	private String entete_codeMVT = "";
	private String entete_codeMVT_NodeId = "";
	private String entete_IdAE = "";
	private String ID_SDS_Unique = "";
	private String generatedId = "";
	private Stack<StringBuffer> chars = new Stack<StringBuffer>();
	private int compteur = 0;
	private String numLigneTexte = "";
		
	/**
	 * Chemins vers les divers éléments que l'on veux lire
	 */
	private static final String CHEMIN_SDS ="/SDS/";
	private static final String CHEMIN_ENTETE = "/ENTETE/";
	private static final String CHEMIN_ENTETE_IDAE = "/ENTETE/ID_AE/";
	private static final String CHEMIN_CODE_MVT = "/ENTETE/CODE_MVT/";
	private static final String RETURN_ANOMALIES_PATH = "/SDS/";
			
	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
		
	}	
	
	
public void startElement(String uri, String localName, String qName,Attributes atts, String xpath) {
		
		if (xpath.endsWith(CHEMIN_SDS)){
			anomalies.clear();
			generatedId = atts.getValue("added:generated-id");
			ID_SDS_Unique = atts.getValue("ano:unique-id");
		}
		if (xpath.endsWith(CHEMIN_ENTETE)){
			entete_IdAE = entete_codeMVT = entete_codeMVT_NodeId = "";
			compteur++;
			if(atts.getValue("txt2xml:LineTxt")!=null){
				numLigneTexte = atts.getValue("txt2xml:LineTxt");
			} else {
				numLigneTexte = "";
			}
		}
		if (xpath.endsWith(CHEMIN_CODE_MVT)){
			entete_codeMVT_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.endsWith(CHEMIN_ENTETE_IDAE)) {
		entete_IdAE = chars.peek().toString();
	}
	if (xpath.endsWith(CHEMIN_CODE_MVT)) {
		entete_codeMVT = chars.peek().toString();
	}

	
	if (xpath.endsWith(CHEMIN_ENTETE)){
		
		if (!entete_codeMVT.equals("501") && !entete_codeMVT.equals("521") &&!entete_codeMVT.equals("701")&&!entete_codeMVT.equals("702")&&!entete_codeMVT.equals("201")&&!entete_codeMVT.equals("551")){

			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, entete_IdAE);
			msg = msg.replaceAll(MSG_ENTETE_CODE_MVT, entete_codeMVT);
						
			String path = "@ano:unique-id='" + ID_SDS_Unique + "'";
			String anoId = IdGenerator.nextId();
			String libelleLien = "Entete "+entete_IdAE;
			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(),
                                    "FEN0071A",
                                    "SDS", // élément importable
                                    entete_IdAE, // 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_codeMVT_NodeId));
			anomalies.add(ano);
		}
		chars.pop();
		return null;
	
	} else if (xpath.endsWith(RETURN_ANOMALIES_PATH)){
		chars.pop();
		return anomalies;
	} else {
		chars.pop();
		return null;
	}
}

public void endDocument() throws SAXException {}

public void characters(char[] ch, int start, int length, String xpath) {
	// on stocke les caractères lus
	chars.peek().append(ch, start, length);
}

public void ignorableWhitespace(char[] ch, int start, int length,String xpath) {}

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

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

public void processingInstruction(String target, String data, String xpath) {}

public void skippedEntity(String name, String xpath) {}

public void setParameters(Hashtable<String,Object> params) {
	this.hParams=params;
}

public void setDocumentLocator(Locator locator) {}
}
