/*
 * Copyright
 *   2007 axYus - www.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.rsa.importer;

import fr.gouv.finances.dgfip.utils.xml.SAXWriter;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.Constants;
import fr.gouv.finances.dgfip.xemelios.common.FileInfo;
import fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter;
import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Stack;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class RSAImporter extends DefaultImporter {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RSAImporter.class);

    public static final String COLLECTIVITE_TYPE_PATH = "/Racine/InfosFinancieresFoyerRSA/IdentificationRSA/Partenaire/TYPEPARTE";
    public static final String COLLECTIVITE_LIB_PATH = "/Racine/InfosFinancieresFoyerRSA/IdentificationRSA/Partenaire/IDEPARTE";
    public static final String PERIODE_PATH = "/Racine/InfosFinancieresFoyerRSA/AcompteRSA/GeneraliteAcompteRSA/MOISMOUCOMPTA";
    private static final String EXPECTED_ERROR = "EXPECTED_ERROR";
    public static final String ETAT_BALISE = "DemandesRSA";
    public static final String ETAT_TOTALISATION = "Totalisations";
    public static final String PERIODE = "Periode";
    private File outputTmpFile;

    public RSAImporter(XemeliosUser user) {
        super(user);
    }

    @Override
    protected FileInfo importFile(File f) throws Exception {
        getImpSvcProvider().startLongWait();
        File newFile = wrapFile(f);
        getImpSvcProvider().endLongWait();
        FileInfo fi = super.importFile(newFile);
        newFile.delete();
        return fi;

    }

    @Override
    public void done() {
        super.done();
    }



    protected File wrapFile(File f) {
        SAXParserFactory fact = SAXParserFactory.newInstance();
        fact.setNamespaceAware(true);
        outputTmpFile = new File(getTmpDir(),f.getName());
        while(outputTmpFile.exists()) {
            if(outputTmpFile.equals(f)) {
                File tmpDir = outputTmpFile.getParentFile();
                tmpDir = new File(tmpDir,"TMP-DIR");
                tmpDir.mkdirs();
                outputTmpFile = new File(tmpDir,f.getName());
            } else {
                outputTmpFile.delete();
            }
        }
        FileOutputStream fos = null;
        try {
            SAXParser collParser = fact.newSAXParser();
            CollHandler handler = new CollHandler(getDocumentModel().getNamespaces());
            String collectivite="";
            String periode = "";
            try {
                collParser.parse(f, handler);
            } catch(SAXException saxEx) {
                if(EXPECTED_ERROR.equals(saxEx.getMessage())) {
                    collectivite = handler.getCollectivite();
                    periode = handler.getPeriode();
                } else {
                    throw saxEx;
                }
            }
            fos = new FileOutputStream(outputTmpFile);
            String encoding = getFileEncoding(f);
            final String passedColl = collectivite;
            final String passedPeriode = periode;
            SAXWriter writer = new SAXWriter(fos, encoding) {
                private boolean alreadyCreatedEtat = false;
                @Override
                public void startDocument() throws SAXException {
                    super.startDocument();
                    startPrefixMapping("added", Constants.ADDED_NS_URI);
//                    startElement(Constants.ADDED_NS_URI, "DocEtatsFrais", new QName(Constants.ADDED_NS_URI, "DocEtatsFrais", "added").toString(),new AttributesImpl());
                }
                @Override
                public void endDocument() throws SAXException {
//                    endElement(Constants.ADDED_NS_URI, "DocEtatsFrais", new QName(Constants.ADDED_NS_URI, "DocEtatsFrais", "added").toString());
                    endPrefixMapping("added");
                    super.endDocument();
                }

                @Override
                public void processingInstruction(String target, String data) throws SAXException {
                    //super.processingInstruction(target, data);
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    super.endElement(uri, localName, qName);
                    if("TotalisationAcompte".equals(localName))
                        endElement(XMLConstants.NULL_NS_URI, ETAT_TOTALISATION, new QName(XMLConstants.NULL_NS_URI,ETAT_TOTALISATION,"").toString());
                }

                @Override
                public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
                    if(!alreadyCreatedEtat && localName.equals("InfosFinancieresFoyerRSA")) {
                        startElement(XMLConstants.NULL_NS_URI, ETAT_BALISE, new QName(XMLConstants.NULL_NS_URI, ETAT_BALISE,"").toString(), new AttributesImpl());
                        alreadyCreatedEtat=true;
                    }
                    if(alreadyCreatedEtat && localName.equals("TotalisationAcompte")) {
                        endElement(XMLConstants.NULL_NS_URI, ETAT_BALISE, new QName(XMLConstants.NULL_NS_URI, ETAT_BALISE,"").toString());
                        startElement(XMLConstants.NULL_NS_URI, ETAT_TOTALISATION, new QName(XMLConstants.NULL_NS_URI,ETAT_TOTALISATION,"").toString(), new AttributesImpl());
                    }
                    super.startElement(uri, localName, qName, atts);
                    if(localName.equals("Racine")) {
                        startElement(Constants.ADDED_NS_URI, "Collectivite", new QName(Constants.ADDED_NS_URI, "Collectivite", "added").toString(),new AttributesImpl());
                        characters(passedColl.toCharArray(), 0, passedColl.length());
                        endElement(Constants.ADDED_NS_URI, "Collectivite", new QName(Constants.ADDED_NS_URI, "Collectivite", "added").toString());
                        AttributesImpl attrs = new AttributesImpl();
                        attrs.addAttribute("", "code", "", "xs:string", "00");
                        attrs.addAttribute("", "libelle", "", "xs:string", "Budget Principal");
                        startElement(Constants.ADDED_NS_URI, "Budget", new QName(Constants.ADDED_NS_URI, "Budget", "added").toString(),attrs);
                        endElement(Constants.ADDED_NS_URI, "Budget", new QName(Constants.ADDED_NS_URI, "Budget", "added").toString());
                        startElement(XMLConstants.NULL_NS_URI, PERIODE, new QName(XMLConstants.NULL_NS_URI, PERIODE,"").toString(), new AttributesImpl());
                        characters(passedPeriode.toCharArray(), 0, passedPeriode.length());
                        endElement(XMLConstants.NULL_NS_URI, PERIODE, new QName(XMLConstants.NULL_NS_URI, PERIODE,"").toString());
                    }
                }


            };
            writer.setPrettyPrint(false);
            SAXParser parser = fact.newSAXParser();
            parser.parse(f, writer);

        } catch(Exception ex) {
            logger.error("wrapFile(File):",ex);
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch(Throwable t) {}
        }
        return outputTmpFile;
    }

    private class CollHandler extends DefaultHandler {
        Stack<QName> stack;
        NamespaceContext nsCtx;
        Stack<StringBuffer> textContent;
        private StringBuffer collectivite;
        private String periode;
        private String firstPart, secondPart;
        private boolean firstPartDone=false, secondPartDone=false, periodeDone=false;

        public String getCollectivite() { return collectivite.toString(); }
        public String getPeriode() { return periode; }

        public CollHandler(NamespaceContext nsCtx) {
            super();
            this.nsCtx=nsCtx;
            stack = new Stack<QName>();
            textContent = new Stack<StringBuffer>();
            collectivite = new StringBuffer();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            QName qname = XmlUtils.getQName(uri, localName, qName);
            stack.push(qname);
            textContent.push(new StringBuffer());
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
            String pathTag = XmlUtils.getPath(stack, nsCtx);
            if(COLLECTIVITE_TYPE_PATH.equals(pathTag)) {
                firstPart = textContent.peek().toString();
                firstPartDone = true;
            } else if(COLLECTIVITE_LIB_PATH.equals(pathTag)) {
                secondPart = textContent.peek().toString();
                secondPartDone = true;
            } else if(PERIODE_PATH.equals(pathTag)) {
                periode = textContent.peek().toString();
                periodeDone = true;
            }
            if(firstPartDone && secondPartDone && periodeDone) {
                collectivite.append(firstPart).append(secondPart);
                throw new SAXException(EXPECTED_ERROR);
            }
            stack.pop();
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            String s = new String(ch,start,length);
            textContent.peek().append(s);
        }
    }
}
