/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2010 C.MARCHAND - christophe.marchand@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.Vector;

import org.apache.commons.io.FilenameUtils;
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;

public class M100 extends AbstractUnitControl {
    public static final transient String CTRL_ID="CTL-M100";
    private static final String RETURN_ANOMALIES_PATH = "FEN0029A/";
    private static final String CHEMIN_ENTETE_IDAE = "ENTETE/ID_AE/";
	private static final String CHEMIN_DPDIRECTE = "/DP_DIRECTE/";
    private String entete_IdAE = null;
	private String ID_DP_DIRECTE_Unique = "";
    private Stack<StringBuffer> chars = new Stack<StringBuffer>();

    public void setDocumentLocator(Locator locator) { }

    public void startDocument() throws SAXException { }

    public void endDocument() throws SAXException { }

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

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

    public void startElement(String uri, String localName, String qName, Attributes atts, String xpath) throws SAXException {
        chars.push(new StringBuffer());

		if (xpath.endsWith(CHEMIN_DPDIRECTE)){
			ID_DP_DIRECTE_Unique = atts.getValue("ano:unique-id");
		}	
    }

    public Vector<Anomalie> endElement(String uri, String localName, String qName, String xpath) throws SAXException {
        Vector<Anomalie> ret = new Vector<Anomalie>();
        if (xpath.endsWith(CHEMIN_ENTETE_IDAE)) {
                entete_IdAE = chars.peek().toString();
        } else if(xpath.endsWith(RETURN_ANOMALIES_PATH)) {
            String fileName = getFileName();

            if(!checkFileName(fileName)) {
                String path = "@ano:unique-id='" + ID_DP_DIRECTE_Unique + "'";
                String anoId = IdGenerator.nextId();
                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),
                        getDocumentModel().getDocumentId(),
                        "FEN0029A",
                        "DP_DIRECTE", // élément importable
                        entete_IdAE, // id élément importable
                        localName,
                        "Nom de fichier invalide",
                        getDocumentModel().getControlById(CTRL_ID).getMessage().getHtmlContent().replace("#FILENAME#", fileName),
                        getDocumentModel().getControlById(CTRL_ID).getRegle().getHtmlContent(),
                        getDocumentModel().getControlById(CTRL_ID).getSeverity(),
                        path,
                        xslParams);
                ret.add(ano);

            }
        }
        chars.pop();
        return ret;
    }

    public void characters(char[] ch, int start, int length, String xpath) throws SAXException {
        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) { }

    public boolean checkFileName(String fileName) {
        boolean bRet = false;
        String baseName = FilenameUtils.getBaseName(fileName);
        if(baseName.length()<31) return false;
        String codeTypeFlux = baseName.substring(0,3);
        if(!codeTypeFlux.equals("FEN")) return false;
        String codeInterface = baseName.substring(3, 7);
        if(!codeInterface.equals("0029")) return false;
        String versionInterface = baseName.substring(7,8);
        // pas de controle sur la version de l'interface
        if(!"_".equals(baseName.substring(8, 9))) return false;
        String appliEmettrice = baseName.substring(9,15);
        // pas de controle sur l'appli emettrice
        if(!"_".equals(baseName.substring(15, 16))) return false;
        String idFlux = baseName.substring(16, 31);
        // pas de controle sur l'id flux
        return true;
    }
}
