/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2010 C ESCOBAR - christel.escobar@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.TreeSet;
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° M004
 * 
 * Il ne peut y avoir deux ENTETE/ID_AE identiques dans un même flux FEN0029A
 */

public class M004 extends AbstractUnitControl {
	private final static Logger logger = Logger.getLogger(M004.class);
    public static final transient String CTRL_ID = "CTL-M004";
	private Hashtable<String,Object> hParams;
	Vector<Anomalie> anomalies = new Vector<Anomalie>();

	/**
	 * Variables devant être remplacées dans le message
	 */

	private static final String MSG_ENTETE_IDAE = "#ENTETE_IDAE#";
	private static final String MSG_ERREUR = "#ERREUR#";
	
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */

	private String entete_IdAE = "";
	private String entete_IdAE_NodeId = "";
	private String ID_DP_DIRECTE_Unique = "";
	private String DP_DIRECTE_Unique = "";
	private String numLigneTexte = "";
		
	private Stack<StringBuffer> chars = new Stack<StringBuffer>();
	
	Vector<String> idAE_values = new Vector<String>();
	Vector<String> idAE_values_erreur = new Vector<String>();
	Hashtable<String,Vector<String>> all_NodeId = new Hashtable<String, Vector<String>>();
	Hashtable<String,Vector<String>> all_ID_DP_DIRECTE_Unique = new Hashtable<String, Vector<String>>();

	private TreeSet<String> treeIdAe = new TreeSet<String>();
			
	/**
	 * Chemins vers les divers éléments que l'on veux lire
	 */
	private static final String CHEMIN_DPDIRECTE = "/DP_DIRECTE/";
	private static final String CHEMIN_ENTETE = "/ENTETE/";
	private static final String CHEMIN_ENTETE_IDAE = "/ENTETE/ID_AE/";
	//private static final String RETURN_ANOMALIES_PATH = "FEN0029A/";
	private static final String RETURN_ANOMALIES_PATH = CHEMIN_DPDIRECTE;
	
	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_DPDIRECTE)){
			ID_DP_DIRECTE_Unique = atts.getValue("ano:unique-id");
			anomalies.clear();
		}
		if (xpath.endsWith(CHEMIN_ENTETE)){
			entete_IdAE = entete_IdAE_NodeId = "";			
			if(atts.getValue("txt2xml:LineTxt")!=null){
				numLigneTexte = atts.getValue("txt2xml:LineTxt");
			} else {
				numLigneTexte = "";
			}
		}
		if (xpath.endsWith(CHEMIN_ENTETE_IDAE)){
			entete_IdAE_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 {
						
		if (xpath.endsWith(CHEMIN_ENTETE_IDAE)) {
			entete_IdAE = chars.peek().toString();
		}
		
		if (xpath.endsWith(RETURN_ANOMALIES_PATH)){
			if (treeIdAe.contains(entete_IdAE)){

				String erreur = "Le dossier est présent plusieurs fois dans le fichier";

				String msg = (numLigneTexte.length()>0?"Ligne n°"+numLigneTexte+" : ":"");
				msg += getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
				msg = msg.replaceAll(MSG_ENTETE_IDAE, entete_IdAE);
				msg = msg.replaceAll(MSG_ERREUR, erreur);				

				String path = "@ano:unique-id='" + ID_DP_DIRECTE_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(),
						"FEN0029A",
						"DP_DIRECTE", // é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_IdAE_NodeId));
				anomalies.add(ano);
			}
			
			treeIdAe.add(entete_IdAE);
			chars.pop();
			return anomalies;
		} else {
			chars.pop();
			return null;
		}
		
		/*if (xpath.endsWith(RETURN_ANOMALIES_PATH)){
			
			if (idAE_values_erreur != null){
				for (int i=0; i<idAE_values_erreur.size(); i++){
					entete_IdAE = idAE_values_erreur.get(i);
					DP_DIRECTE_Unique=all_ID_DP_DIRECTE_Unique.get(entete_IdAE).get(i);
					
					String erreur = "Le dossier est présent plusieurs fois dans le fichier";
					
					String msg = (numLigneTexte.length()>0?"Ligne n°"+numLigneTexte+" : ":"");
					msg += getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
					msg = msg.replaceAll(MSG_ENTETE_IDAE, entete_IdAE);
					msg = msg.replaceAll(MSG_ERREUR, erreur);				
					
					String path = "@ano:unique-id='" + DP_DIRECTE_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(),
	                                        "FEN0029A",
	                                        "DP_DIRECTE", // é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);
					if (all_NodeId.containsKey(entete_IdAE)){
						Vector<String> nodes = all_NodeId.get(entete_IdAE);
						for (int j=0; j<nodes.size(); j++){
							ano.addNode(new Node(nodes.get(j)));
						}
					}
					anomalies.add(ano);
				}
			}
			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) {}
}
