/*
 * Copyright 
 *   2010 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 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
 */

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° M003
 * 
 * La zone AE TYPE_TIERS peut prendre les valeurs suivantes : 'ZCOM', 'ZCPD', 'ZETR', 'ZEUR', 'ZFRA', 'ZPHY', 'ZREG', 'ZSRV', 'ZTAE'.
 */

public class M003 extends AbstractUnitControl {
	private final static Logger logger = Logger.getLogger(M003.class);
    public static final transient String CTRL_ID = "CTL-M003";
	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_DPDIRECTE#";
	private static final String MSG_ENTETE_IDAE = "#ENTETE_IDAE#";
	private static final String MSG_ENTETE_TYPETIERS = "#ENTETE_TYPETIERS#";
	private static final String MSG_ERREUR = "#ERREUR#";
	
	/**
	 * Variables contenant les valeurs nécessaires à ce contrôle
	 */

	private String entete_TypeTiers = "";
	private String entete_TypeTiers_NodeId = "";
	private String entete_IdAE = "";
	private String ID_DP_DIRECTE_Unique = "";
		
	private Stack<StringBuffer> chars = new Stack<StringBuffer>();
	private int compteur = 0;
	
			
	/**
	 * 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 CHEMIN_ENTETE_TYPETIERS = "/ENTETE/TYPE_TIERS/";
	private static final String RETURN_ANOMALIES_PATH = "/DP_DIRECTE/";
			
	
	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)){
			anomalies.clear();
			ID_DP_DIRECTE_Unique = atts.getValue("ano:unique-id");
		}		
		if (xpath.endsWith(CHEMIN_ENTETE)){
			entete_IdAE = entete_TypeTiers = entete_TypeTiers_NodeId = "";
			compteur++;
		}
		if (xpath.endsWith(CHEMIN_ENTETE_TYPETIERS)){
			entete_TypeTiers_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 {
		Vector<String> valeursPossibles = new Vector<String>();
		valeursPossibles.add("ZCOM");valeursPossibles.add("ZCPD");valeursPossibles.add("ZETR");valeursPossibles.add("ZEUR");valeursPossibles.add("ZFRA");valeursPossibles.add("ZPHY");
		valeursPossibles.add("ZREG");valeursPossibles.add("ZSRV");valeursPossibles.add("ZTAE");
		
		String erreur = "";

		
		if (xpath.endsWith(CHEMIN_ENTETE_IDAE)) {
			entete_IdAE = chars.peek().toString();
		}
		if (xpath.endsWith(CHEMIN_ENTETE_TYPETIERS)) {
			entete_TypeTiers = chars.peek().toString();
		}

		
		if (xpath.endsWith(CHEMIN_ENTETE)){
			
			if (!valeursPossibles.contains(entete_TypeTiers)){
				
				erreur = "Les valeurs autorisées de la zone TYPE_TIERS ne sont pas respectées";
				
				String 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_TYPETIERS, entete_TypeTiers);
				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_TypeTiers_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) {}
}
