/*
 * 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.etatFrais;

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.FileInputStream;
import java.io.FileOutputStream;
import java.util.Stack;
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 EtatFraisImporter extends DefaultImporter {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(EtatFraisImporter.class);

    public static final String COLLECTIVITE_PATH = "/ef:EtatsFrais/ef:Invoice/cac:AccountingCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID";
    private static final String EXPECTED_ERROR = "EXPECTED_ERROR";
    private File outputTmpFile;

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

    @Override
    protected FileInfo importFile(File f) throws Exception {
        getImpSvcProvider().startLongWait();
        File newFile = wrapFile(f);

        return super.importFile(newFile);
    }

    @Override
    protected void done() {
        super.done();
//        outputTmpFile.delete();
    }



    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="";
            try {
                collParser.parse(f, handler);
            } catch(SAXException saxEx) {
                if(EXPECTED_ERROR.equals(saxEx.getMessage())) {
                    collectivite = handler.getCollectivite();
                } else {
                    throw saxEx;
                }
            }
            fos = new FileOutputStream(outputTmpFile);
            String encoding = getFileEncoding(f);
            final String passedColl = collectivite;
            SAXWriter writer = new SAXWriter(fos, encoding) {
                @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());
                    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());
                }
                @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);
                }

            };
            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 String collectivite;

        public String getCollectivite() { return collectivite; }

        public CollHandler(NamespaceContext nsCtx) {
            super();
            this.nsCtx=nsCtx;
            stack = new Stack<QName>();
            textContent = new Stack<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);
//            String pathTag = XmlUtils.getPath(stack, nsCtx);
            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_PATH.equals(pathTag)) {
                collectivite = textContent.peek().toString();
                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).trim();
            textContent.peek().append(s);
        }



    }

}
