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


import java.io.File;
import java.io.FileOutputStream;

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 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 javax.xml.namespace.QName;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class RefCollecSplImporter extends DefaultImporter {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RefCollecSplImporter.class);
    public static final transient String REF_COLLEC_SPL_NS = "dgfip:collectivite.spl";

    private File outputTmpFile;

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

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

    @Override
    public 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 {
            fos = new FileOutputStream(outputTmpFile);
            String encoding = getFileEncoding(f);
            SAXWriter writer = new SAXWriter(fos, encoding) {
                @Override
                public void startElement(String uri, String localName, String qName, Attributes attribues) throws SAXException {
                    if(REF_COLLEC_SPL_NS.equals(uri) && "Referentiel".equals(localName)) {
                        super.startPrefixMapping("n", REF_COLLEC_SPL_NS);
                        super.startPrefixMapping("added", Constants.ADDED_NS_URI);
                    }
                    super.startElement(uri, localName, qName, attribues);
                    if(REF_COLLEC_SPL_NS.equals(uri) && "Referentiel".equals(localName)) {
                        AttributesImpl collAttrs = new AttributesImpl();
                        collAttrs.addAttribute("", "code", "", "xs:string", "0000");
                        collAttrs.addAttribute("", "libelle", "", "xs:string", "Référentiel");
                        super.startElement(Constants.ADDED_NS_URI,"Coll",new QName(Constants.ADDED_NS_URI,"Coll", "added").toString(),collAttrs);
                        super.endElement(Constants.ADDED_NS_URI,"Coll",new QName(Constants.ADDED_NS_URI,"Coll", "added").toString());
                        collAttrs = new AttributesImpl();
                        collAttrs.addAttribute("", "code", "", "xs:string", "00");
                        collAttrs.addAttribute("", "libelle", "", "xs:string", "--");
                        super.startElement(Constants.ADDED_NS_URI,"Budg",new QName(Constants.ADDED_NS_URI,"Budg", "added").toString(),collAttrs);
                        super.endElement(Constants.ADDED_NS_URI,"Budg",new QName(Constants.ADDED_NS_URI,"Budg", "added").toString());
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    super.endElement(uri, localName, qName);
                    if(REF_COLLEC_SPL_NS.equals(uri) && "Referentiel".equals(localName)) {
                        super.endPrefixMapping("n");
                        super.endPrefixMapping("added");
                    }
                }

            };
//            writer.getnsContext().addMapping("n", REF_COLLEC_SPL_NS);
//            writer.getnsContext().addMapping("", REF_COLLEC_SPL_NS);
            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;
    }


}
