/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 N.Le Corre - nicolas.lecorre@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.cp.xemelios.controls.paye;

import java.util.Hashtable;
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;

public class PAY07 extends AbstractUnitControl {
	private final static Logger logger = Logger.getLogger(PAY07.class);
    public static final transient String CTRL_ID = PAY07.class.getSimpleName();
	private Vector<Anomalie> anos = new Vector<Anomalie>();
	private String docId = null;

	
	private static final String ON_RETURN_ANOMALIES = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/";
	private static final String CHEMIN_PK_ANNEE = "DocumentPaye/Annee/";
	private static final String CHEMIN_PK_MOIS = "DocumentPaye/Mois/";
	private static final String CHEMIN_PAYE = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/";
	private static final String CHEMIN_PK_MATRICULE = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/Agent/Matricule/";
	private String pk_annee = "", pk_mois = "", pk_matricule = "";
	private String payeNodeId = "";


	private static final String CHEMIN_COMPTE = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/Agent/CptBancaire/";
	private static final String CHEMIN_COMPTE_CODE_ETAB = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/Agent/CptBancaire/CodeEtab/";
	private static final String CHEMIN_COMPTE_CODE_GUIC = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/Agent/CptBancaire/CodeGuic/";
	private static final String CHEMIN_COMPTE_ID_COMPTE = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/Agent/CptBancaire/IdCpte/";
	private static final String CHEMIN_COMPTE_CLE_RIB = "DocumentPaye/DonneesIndiv/PayeIndivMensuel/Agent/CptBancaire/CleRib/";
	private static final String REPLACE_PAYE = "##PAYE##";
	private static final String REPLACE_COMPTE = "##COMPTE##";
	private String compte_code_etab = "", compte_code_guic = "", compte_id_compte = "", compte_cle_rib = "";
	private String compte_code_etabNodeId = "", compte_code_guicNodeId = "", compte_id_compteNodeId = "", compte_cle_ribNodeId = "";
	
	public void startDocument() throws SAXException {
		logger.info("In "+CTRL_ID);
	}
	
	public void setDocId(String docID) {
		this.docId = docID;		
	}

	public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) throws SAXException {
		if (xpath.endsWith(CHEMIN_PAYE)) {
			anos = new Vector<Anomalie>();
			payeNodeId = atts.getValue("ano:node-id");
			pk_matricule = "";
		} else if (xpath.endsWith(CHEMIN_PK_ANNEE)) {
			pk_annee = atts.getValue("V");
		} else if (xpath.endsWith(CHEMIN_PK_MOIS)) {
			pk_mois = atts.getValue("V");
		} else if (xpath.endsWith(CHEMIN_PK_MATRICULE)) {
			pk_matricule = atts.getValue("V");
		} else if (xpath.endsWith(CHEMIN_COMPTE)) {
			compte_code_etab = compte_code_guic = compte_id_compte = compte_cle_rib = "";
			compte_code_etabNodeId = compte_code_guicNodeId = compte_id_compteNodeId = compte_cle_ribNodeId = "";
		} else if (xpath.endsWith(CHEMIN_COMPTE_CLE_RIB)) {
			compte_cle_rib = atts.getValue("V");
			compte_cle_ribNodeId = atts.getValue("ano:node-id");
		} else if (xpath.endsWith(CHEMIN_COMPTE_ID_COMPTE)) {
			compte_id_compte = atts.getValue("V");
			compte_id_compteNodeId = atts.getValue("ano:node-id");
		} else if (xpath.endsWith(CHEMIN_COMPTE_CODE_GUIC)) {
			compte_code_guic = atts.getValue("V");
			compte_code_guicNodeId = atts.getValue("ano:node-id");
		} else if (xpath.endsWith(CHEMIN_COMPTE_CODE_ETAB)) {
			compte_code_etab = atts.getValue("V");
			compte_code_etabNodeId = atts.getValue("ano:node-id");
		}
	}

	public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
		if (xpath.endsWith(ON_RETURN_ANOMALIES)) {
			return anos;
		} else if (xpath.endsWith(CHEMIN_COMPTE)) {
			// ANOMALIE
			if (!validateRib (compte_code_etab, compte_code_guic, compte_id_compte, compte_cle_rib)) {
				String msg = getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent();
				msg = msg.replaceAll(REPLACE_PAYE, pk_annee+" / "+pk_mois+" / "+pk_matricule);
				msg = msg.replaceAll(REPLACE_COMPTE, compte_code_etab+" / "+compte_code_guic+" / "+compte_id_compte+" / "+compte_cle_rib);
				String path="@added:primary-key='"+pk_annee+"-"+pk_mois+"-"+pk_matricule+"'";
				String anoId = IdGenerator.nextId();
				String libelleLien = "";
				Hashtable<String, Object> xslParams = new Hashtable<String, Object>();
				xslParams.put("elementId", "Paye");
				xslParams.put("browser-destination", "internal");
				xslParams.put("anoId", anoId);
				Anomalie ano = new Anomalie(anoId,
											getDocumentModel().getControlById(CTRL_ID).getId(),
											getDocumentModel().getControlById(CTRL_ID).getLibelle(),
											getDocumentModel().getDocumentId(),
											"etatPaye",
											"payeIndivMensuel", // élément importable
											payeNodeId, // id élément importable
											localName,
											libelleLien,
											msg,
											getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
											getDocumentModel().getControlById(CTRL_ID).getSeverity(),
											path, // xpath vers le bordereau sous lequel se trouve l'anomalie
											xslParams); // paramètres supplémentaires pour accéder à l'élément en anomalie
				ano.addNode(new Node(compte_code_etabNodeId));
				ano.addNode(new Node(compte_code_guicNodeId));
				ano.addNode(new Node(compte_id_compteNodeId));
				ano.addNode(new Node(compte_cle_ribNodeId));
				anos.add(ano);
			}
			return null;
		} else {
			return null;
		}
	}

	public boolean validateRib (String codeEtab, String codeGuich, String idCpte, String cleRib) {
		boolean ret = false;
		
		// conversion du numéro de compte en chiffres
		String tabPossibles = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		char []tabTranscrit = "123456789123456789234567890123456789".toCharArray();
		
		String compte = "";
		idCpte = idCpte.toUpperCase();
		for (int i=0; i<idCpte.length(); i++) {
			compte += tabTranscrit[tabPossibles.indexOf(idCpte.charAt(i))];
		}
		
		// calcul de la celf rib du compte
		int bqe = 0;
                try {
                    bqe = Integer.parseInt(codeEtab);
                } catch(NumberFormatException nfEx) {}
		int gui = 0;
                try {
                    gui = Integer.parseInt(codeGuich);
                } catch(NumberFormatException nfEx) {}
		long cp  = 0;
                try {
                    cp = Long.parseLong(compte);
                } catch(NumberFormatException nfEx) {}
		long a=bqe%97;
		a=a*100000+gui;
		a=a%97;
		a=(long)(a*Math.pow(10, 11)) + cp;
		a=a%97;
		a=a*100;
		a=a%97;
		a=97-a;
		
		// la clef est elle la même que celle passée ?
		double cr = Integer.parseInt(cleRib);
		ret = (cr == a);
		
		return ret;
	}
	
	public void characters(char[] ch, int start, int length, String xpath) throws SAXException { }

	public void endDocument() throws SAXException { }

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

	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 setDocumentLocator(Locator locator) { }

	public void setParameters(Hashtable<String, Object> params) { }

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

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

}
