/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 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.cp.xemelios.edmn.importer;

import fr.gouv.finances.cp.utils.xml.SAXWriter;
import fr.gouv.finances.cp.xemelios.common.Constants;
import fr.gouv.finances.cp.xemelios.common.FileInfo;
import fr.gouv.finances.cp.xemelios.common.config.DocumentModel;
import fr.gouv.finances.cp.xemelios.importers.DefaultImporter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author chm
 */
public class EdmnImporter extends DefaultImporter {
    public static final String EDMN_NS_URI = "http://projets.admisource.gouv.fr/xemelios/namespaces#edmn";
    private static final Logger logger = Logger.getLogger(EdmnImporter.class);

    public EdmnImporter() {
        super();
    }

    @Override
    public void setDocument(DocumentModel dm) {
        this.dm = dm;
    }

    @Override
    protected FileInfo importFile(File f) throws Exception {
        FileInfo ret = new FileInfo();
        
        getImpSvcProvider().startLongWait();
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        tmpDir = new File(tmpDir,Constants.NOM_APP);
        tmpDir.mkdirs();
        File xmlFile = File.createTempFile(f.getName(), ".xml", tmpDir);
        generateXmlFile(f,xmlFile);
        getImpSvcProvider().endLongWait();

        return super.importFile(xmlFile);
    }
    
    protected void generateXmlFile(File source, File dest) throws IOException, SAXException {
        OutputStream os = new FileOutputStream(dest);
        SAXWriter sWriter = new SAXWriter(os, "ISO-8859-1");
        BufferedReader br = new BufferedReader(new FileReader(source));
        String line = br.readLine();
        sWriter.startDocument();
        sWriter.startPrefixMapping("n", EDMN_NS_URI);
        sWriter.startElement(EDMN_NS_URI,"Edmn","n:Edmn",new AttributesImpl());
        sWriter.startElement(EDMN_NS_URI,"EtatEdmn","n:EtatEdmn",new AttributesImpl());
        while(line!=null) {
            EdmnStruct es = new EdmnStruct(line);
            es.writeXml(sWriter);
            line = br.readLine();
        }
        sWriter.endPrefixMapping("n");
        sWriter.endElement(EDMN_NS_URI,"EtatEdmn","n:EtatEdmn");
        sWriter.endElement(EDMN_NS_URI,"Edmn","n:Edmn");
        sWriter.endDocument();
        os.flush();
        os.close();
    }

    @Override
    public String getAdditionalMessage() {
        return "";
    }
    
    private class EdmnStruct {
        private String cble  =""    ;//      6     1
        private String imin  =""    ;//      3     7
        private String ctordo =""   ;//      6    10
        private String tyeven =""   ;//      3    16
        private String angest =""   ;//      2    19
        private String nomdt  =""   ;//      6    21
        private String rccst  =""   ;//      5    27
        private String noopin =""   ;//      8    32
        private String daenga =""   ;//      2    40
        private String noeng  =""   ;//      6    42
        private String ichap  =""   ;//      4    48
        private String iart   =""   ;//      2    52
        private String iparag =""   ;//      2    54
        private String mtedm  =""   ;//     13    56
        private String cosimo =""   ;//      1    69
        private String datrim =""   ;//      1    70
        private String damois =""   ;//      2    71
//        private String dacre8    ;//           73
        private String siecle =""   ;//      4    73
        private String comois  =""  ;//      2    77
        private String jour  =""    ;//      2    79
        private String ichacl =""   ;//      4    81
        private String cttypa =""   ;//      3    85
        private String ciarbp =""   ;//      2    88
        private String wf24 =""     ;//     24    90
        private String nolia1 =""   ;//      4   114
        private String nolia2  =""  ;//      4   118
        private String cotys1  =""  ;//      2   122
        private String cotys2 =""   ;//      2   124
        private String cotys3 =""   ;//      2   126
        private String codaco  =""  ;//      4   128
        private String noliac =""   ;//      6   132
        private String comane =""   ;//      1   138
        private String wf32  =""    ;//     32   139
        
        public EdmnStruct(String line) {
            super();
//            logger.debug(line);
            cble=line.substring(0, 6);
            imin=line.substring(6, 9);
            ctordo=line.substring(9, 15);
            tyeven=line.substring(15, 18);
            angest=line.substring(18, 20);
            nomdt=line.substring(20, 26);
            rccst=line.substring(26, 31);
            noopin=line.substring(31, 39);
            daenga=line.substring(39, 41);
            noeng=line.substring(41, 47);
            ichap=line.substring(47, 51);
            iart=line.substring(51, 53);
            iparag=line.substring(53, 55);
            mtedm=line.substring(55, 68);
            cosimo=line.substring(68, 69);
            datrim=line.substring(69, 70);
            damois=line.substring(70, 72);
            siecle=line.substring(72, 76);
            comois=line.substring(76, 78);
            jour=line.substring(78, 80);
            ichacl=line.substring(80, 84);
            cttypa=line.substring(84, 87);
            ciarbp=line.substring(87, 89);
            wf24=line.substring(89, 113);
            nolia1=line.substring(113, 117);
            nolia2=line.substring(117, 121);
            cotys1=line.substring(121, 123);
            cotys2=line.substring(123, 125);
            cotys3=line.substring(125, 127);
            codaco=line.substring(127, 131);
            noliac=line.substring(131, 137);
            comane=line.substring(137, 138);
            wf32=line.substring(138, 170);
        }
        
        public void writeXml(DefaultHandler h) throws SAXException {
            h.startElement(EDMN_NS_URI, "LigneEdmn", "n:LigneEdmn", new AttributesImpl());
            writeNode("Comptable", cble, h);
            writeNode("Ministere",imin,h);
            writeNode("Ordo",ctordo,h);
            writeNode("TypeEvt",tyeven,h);
            writeNode("AnneeBudget",angest,h);
            writeNode("NumMandat",nomdt,h);
            writeNode("CompteSpeTresor",rccst,h);
            writeNode("NumOpeInvest",noopin,h);
            writeNode("AnneeEngag",daenga,h);
            writeNode("NumEngag",noeng,h);
            writeNode("ChapBudg",ichap,h);
            writeNode("ArtBudgExec",iart,h);
            writeNode("ParagBudgExec",iparag,h);
            while(mtedm.startsWith("0")) mtedm = mtedm.substring(1);
            if(cosimo.trim().equals("-")) mtedm = "-"+mtedm;
            writeNode("MtPJ",mtedm,h);
//            writeNode("SigneMt",cosimo,h);
            writeNode("Trimestre",datrim,h);
            writeNode("Mois",damois, h);
            writeNode("AnneeCrea",siecle,h);
            writeNode("MoisCrea",comois,h);
            writeNode("JourCrea",jour,h);
            writeNode("DateCreation",siecle+"-"+comois+"-"+jour,h);
            writeNode("ChapClassPJ",ichacl,h);
            writeNode("TypePaiement",cttypa,h);
            writeNode("ArtBudgPrev",ciarbp,h);
            writeNode("Zone24",wf24,h);
            writeNode("NumLiasse",nolia1+nolia2,h);
//            writeNode("NumLiasse2",nolia2,h);
            writeNode("TypeSuiviEco1",cotys1,h);
            writeNode("TypeSuiviEco2",cotys2,h);
            writeNode("TypeSuiviEco3",cotys3,h);
            writeNode("CodeCorrection",codaco,h);
            writeNode("NumLiasseCentrale",noliac,h);
            writeNode("CodeManip",comane,h);
            writeNode("Zome32", wf32, h);
            h.endElement(EDMN_NS_URI, "LigneEdmn", "n:LigneEdmn");
        }
        protected void writeNode(String nodeName, String value, DefaultHandler h) throws SAXException {
            AttributesImpl attr = new AttributesImpl();
            attr.addAttribute("", "V", "V", "String", value);
            h.startElement(EDMN_NS_URI, nodeName, "n:"+nodeName, attr);
            h.endElement(EDMN_NS_URI, nodeName, "n:"+nodeName);
        }
    }
}
