
package fr.gouv.finances.dgfip.xemelios.entreesdirectesstock;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import fr.gouv.finances.dgfip.xemelios.txt2xml.AbstractTxt2Xml;
import fr.gouv.finances.dgfip.xemelios.txt2xml.Txt2Xml;

public class EntreesDirectesStockTxt2Xml extends AbstractTxt2Xml implements Txt2Xml {

    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(EntreesDirectesStockTxt2Xml.class);
    private final static String ENCODING_TXT = "UTF-8";
    private final static String ENCODING_XML = "ISO-8859-15";
    private final static int LENGTH_ENTETE = 360;
    private final static int LENGTH_LINE = 703;
    private final static int LENGTH_LINE_INCONNUE = 703;
    private final static String TAG_FEN = "FEN0070A";
    private final static String TAG_ETAT = "EDS";
    private final static String TAG_ENTETE = "ENTETE";
    private final static String TAG_LIGNE = "POSTE";
    private final static String TAG_LIGNE_INCONNUE = "LIGNE_INCONNUE";

    private final static String NAMESPACE = "FEN0070A";

    public EntreesDirectesStockTxt2Xml() {
        super();
    }
    /*
    public static void main(final String[] args) {
    DpDirecteTxt2Xml thisDP = new DpDirecteTxt2Xml();
    thisDP.transform(new File("C:/TEMP/AIFE/FEN0029A/FEN0029A_SIS001_SIS001002900151"));
    }         
     */

    public boolean isXmlFile(File input, String encoding) {
        boolean ret = false;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input), encoding));
            String line = br.readLine();
            int i = 0;
            while (line != null) {
                if (line.trim().length() > 0) {
                    i++;
                    if (i == 1 && line.trim().matches("[<][?]xml version[=].* encoding[=].*[?][>]")) {
                        return true;
                    } else {
                        return false;
                    }
                }
                line = br.readLine();
            }
        } catch (Exception e) {
            logger.debug("Problème dans isXmlFile() :\n", e);
        }
        return ret;
    }

    public File transform(File f) {
        File ret = null;
        try {
            if (isXmlFile(f, ENCODING_TXT)) {
                ret = f;
            } else {
                ret = makeTransformEntreesDirectesStock(f);
            }
        } catch (Exception e) {
            logger.debug("Problème de transformation du flux !", e);
        }
        return ret;
    }

    /**
     * @param f
     * @return
     * @throws IOException
     */
    private File makeTransformEntreesDirectesStock(File f) throws IOException {

//		File outputFile = new File("C:/TEMP/AIFE", "tmp-"+f.getName()+".xml"); /* Avec la main */
        File outputFile = new File(System.getProperty("java.io.tmpdir"), f.getName());
        outputFile.createNewFile();

        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(outputFile);
            fos.write(("<?xml version=\"1.0\" encoding=\"" + ENCODING_XML + "\"?>\n<"+TAG_FEN+" xmlns=\""+NAMESPACE+"\" xmlns:txt2xml=\"http://www.xemelios.org/namespaces#txt2xml\">\n").getBytes(ENCODING_XML));
            fis = new FileInputStream(f);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, ENCODING_TXT));
            String line = br.readLine();
            int nbLignesParcourues = 0;
            while (line != null) {
                nbLignesParcourues++;
                if (line.trim().length() > 0) {
                    if (line.substring(0, 1).equals("E")) {
                        fos.write(makeTranformEntete(line, nbLignesParcourues));
                    } else if (line.substring(0, 1).equals("L")) {
                        fos.write(makeTranformLine(line, nbLignesParcourues));
                    }
                    else if ((!line.substring(0, 1).equals("L"))&& (!line.substring(0, 1).equals("E"))) {
                        System.out.println("isLineUnknown!");                  	
                                            fos.write(makeTranformLineInconnue(line, nbLignesParcourues)); 
                                        }
                                        
                }
                line = br.readLine();
            }
            fos.write(("\t</"+TAG_ETAT+">\n</"+TAG_FEN+">").getBytes(ENCODING_XML));
            fos.flush();
        } catch (UnsupportedEncodingException uee) {
            logger.debug("Problème d'écriture avec encoding !");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        logger.info("Le fichier de sortie de transformation se trouve ici : " + outputFile.getAbsolutePath());
        return outputFile;
    }

    private byte[] makeTranformEntete(String line, int nbLignesParcourues) throws UnsupportedEncodingException {
        StringBuffer sb = null;
        if (nbLignesParcourues > 1) {
            sb = new StringBuffer("\t</"+TAG_ETAT+">\n\t<"+TAG_ETAT+">\n\t\t<"+TAG_ENTETE+" txt2xml:LineTxt=\"" + nbLignesParcourues + "\">\n");
        } else {
            sb = new StringBuffer("\t<"+TAG_ETAT+">\n\t\t<"+TAG_ENTETE+" txt2xml:LineTxt=\"" + nbLignesParcourues + "\">\n");
        }
        /* Compris entre LENGTH_ENTETE-2 && LENGTH_ENTETE */
        if (line.length() >= LENGTH_ENTETE-1) {
            /* Variables à récupérer
             * 		Lot3 - Format pivot AE FEN0070A - Réception des demandes de paiement directes V2.2.doc
             */
            try {           
        
                String codeAppli = line.substring(1,7);
                String idAe = line.substring(7,23);
                String dateCpt = line.substring(23,31);
                String datePhy = line.substring(31, 39);
                String billOfLading = line.substring(39, 55);
                String codeMvt = line.substring(55, 58);
                String motifMvt = line.substring(58, 62);
                String grGiSlipNo  = line.substring(62, 72);
                String prUname = line.substring(72, 84);
                String txtEntete = line.substring(84, 109);
                
                sb.append("\t\t\t<CODE_APPLI txt2xml:TxtValue=\"").append(codeAppli).append("\">").append(codeAppli.trim()).append("</CODE_APPLI>\n");
                sb.append("\t\t\t<ID_AE txt2xml:TxtValue=\"").append(idAe).append("\">").append(idAe.trim()).append("</ID_AE>\n");
                sb.append("\t\t\t<DATE_CPT txt2xml:TxtValue=\"").append(dateCpt).append("\">").append(dateCpt.trim()).append("</DATE_CPT>\n");
                sb.append("\t\t\t<DATE_PHY txt2xml:TxtValue=\"").append(datePhy).append("\">").append(datePhy.trim()).append("</DATE_PHY>\n");
                if (billOfLading.trim().length() > 0) {
                sb.append("\t\t\t<BILL_OF_LADING txt2xml:TxtValue=\"").append(billOfLading).append("\">").append(billOfLading.trim()).append("</BILL_OF_LADING>\n");
                }              
              
                sb.append("\t\t\t<CODE_MVT txt2xml:TxtValue=\"").append(codeMvt).append("\">").append(codeMvt.trim()).append("</CODE_MVT>\n");
 
                
                if (motifMvt.trim().length() > 0) {

                    sb.append("\t\t\t<MOTIF_MVT txt2xml:TxtValue=\"").append(motifMvt).append("\">").append(motifMvt.trim()).append("</MOTIF_MVT>\n");
                    }
                if (grGiSlipNo.trim().length() > 0) {
                sb.append("\t\t\t<GR_GI_SLIP_NO txt2xml:TxtValue=\"").append(grGiSlipNo).append("\">").append(grGiSlipNo.trim()).append("</GR_GI_SLIP_NO>\n");
                }
                sb.append("\t\t\t<PR_UNAME txt2xml:TxtValue=\"").append(prUname).append("\">").append(prUname.trim()).append("</PR_UNAME>\n");
                sb.append("\t\t\t<TXT_ENTETE txt2xml:TxtValue=\"").append(txtEntete).append("\">").append(txtEntete.trim()).append("</TXT_ENTETE>\n");

            } catch (Exception e) {
                System.out.println("ENTETE : Erreur de transfmormation : " + line);
            }
        } else {
        	logger.debug("Longueur de " + line.length()+" : " + (LENGTH_ENTETE - 2) +" <= "+ line.length() + " <= "+ LENGTH_ENTETE);
        }
        sb.append("\t\t</"+TAG_ENTETE+">\n");
        return sb.toString().getBytes(ENCODING_XML);
    }

    private byte[] makeTranformLine(String line, int nbLignesParcourues) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer("\t\t<"+TAG_LIGNE+" txt2xml:LineTxt=\"" + nbLignesParcourues + "\">\n");
        if (line.length() >= LENGTH_LINE-1) { 
        
            String  idAe  = line.substring(1,17);				
            String  IdLing = line.substring(17, 23);				
            String  typeIdFonc = line.substring(23,53);				
            String  idFoncProd= line.substring(53,83);				
            String  idChorusProd = line.substring(83,101);				
            String  plant = line.substring(101,105); 				
            String  stgeLoc = line.substring(105,109);				
            String  idFoncPartner = line.substring(109,189);				
            String  GRcomptespartner = line.substring(189,193);				
            String  idChourusPartner = line.substring(193,203);				
            String  quantity= line.substring(203,218);				
            String  unit= line.substring(218,221);				
            String  val= line.substring(221,246);				
            String  poNumber= line.substring(246, 256);				
            String  poItem= line.substring(256,261);				
            String  txtPst = line.substring(261,311);				
            String  recept= line.substring(311,323);				
            String  webElem= line.substring(323,347);				
            String  idFoncSuppl = line.substring(347, 427);				
            String  grcomptessuppl = line.substring(427, 431);				
            String  idChourusSuppl = line.substring(431, 441);				
            String  funcArea = line.substring(441, 457);				
            String  anaMin= line.substring(457,479);				
            String  locMin = line.substring(479, 501);				
            String  natMin= line.substring(501, 512);				
            String  axmin1 = line.substring(512, 534);				
            String	axmin2=line.substring(534,556);
            

            sb.append("\t\t\t<ID_AE txt2xml:TxtValue=\"").append(idAe).append("\">").append(idAe.trim()).append("</ID_AE>\n");
            sb.append("\t\t\t<ID_LIG txt2xml:TxtValue=\"").append(IdLing).append("\">").append(IdLing.trim()).append("</ID_LIG>\n");
           
            if (typeIdFonc.trim().length() > 0) {
            sb.append("\t\t\t<TYPE_ID_FONC txt2xml:TxtValue=\"").append(typeIdFonc).append("\">").append(typeIdFonc.trim()).append("</TYPE_ID_FONC>\n");
           }
            if (idFoncProd.trim().length() > 0) {
            sb.append("\t\t\t<ID_FONC_PROD txt2xml:TxtValue=\"").append(idFoncProd).append("\">").append(idFoncProd.trim()).append("</ID_FONC_PROD>\n");
            }
             if (idChorusProd.trim().length() > 0) {
            sb.append("\t\t\t<ID_CHORUS_PROD txt2xml:TxtValue=\"").append(idChorusProd).append("\">").append(idChorusProd.trim()).append("</ID_CHORUS_PROD>\n");
            }
            
            sb.append("\t\t\t<PLANT txt2xml:TxtValue=\"").append(plant).append("\">").append(plant.trim()).append("</PLANT>\n");
            sb.append("\t\t\t<STGE_LOC txt2xml:TxtValue=\"").append(stgeLoc).append("\">").append(stgeLoc.trim()).append("</STGE_LOC>\n");
            
            if (idFoncPartner.trim().length() > 0) {
                sb.append("\t\t\t<ID_FONC_PARTNER txt2xml:TxtValue=\"").append(idFoncPartner).append("\">").append(idFoncPartner.trim()).append("</ID_FONC_PARTNER>\n");
            }
            
            if (GRcomptespartner.trim().length() > 0) {
                sb.append("\t\t\t<GR_COMPTES_PARTNER txt2xml:TxtValue=\"").append(GRcomptespartner).append("\">").append(GRcomptespartner.trim()).append("</GR_COMPTES_PARTNER>\n");
            }
             if (idChourusPartner.trim().length() > 0) {
            sb.append("\t\t\t<ID_CHORUS_PARTNER txt2xml:TxtValue=\"").append(idChourusPartner).append("\">").append(idChourusPartner.trim()).append("</ID_CHORUS_PARTNER>\n");
            }
            
            sb.append("\t\t\t<QUANTITY txt2xml:TxtValue=\"").append(quantity).append("\">").append(quantity.trim()).append("</QUANTITY>\n");
            
            if (unit.trim().length() > 0) {
            sb.append("\t\t\t<UNIT txt2xml:TxtValue=\"").append(unit).append("\">").append(unit.trim()).append("</UNIT>\n");
            }

           if (val.trim().length() > 0) {
            sb.append("\t\t\t<VAL txt2xml:TxtValue=\"").append(val).append("\">").append(val.trim()).append("</VAL>\n");
            }
            if (poNumber.trim().length() > 0) {
                sb.append("\t\t\t<PO_NUMBER txt2xml:TxtValue=\"").append(poNumber).append("\">").append(poNumber.trim()).append("</PO_NUMBER>\n");
                
            }
            if (poItem.trim().length() > 0) {
            sb.append("\t\t\t<PO_ITEM txt2xml:TxtValue=\"").append(poItem).append("\">").append(poItem.trim()).append("</PO_ITEM>\n");
            }
            if (txtPst.trim().length() > 0) {
                sb.append("\t\t\t<TXT_PST txt2xml:TxtValue=\"").append(txtPst).append("\">").append(txtPst.trim()).append("</TXT_PST>\n");
            }
            if (recept.trim().length() > 0) {
            sb.append("\t\t\t<RECEPT txt2xml:TxtValue=\"").append(recept).append("\">").append(recept.trim()).append("</RECEPT>\n");
            }
            if (webElem.trim().length() > 0) {
                sb.append("\t\t\t<WBS_ELEM txt2xml:TxtValue=\"").append(webElem).append("\">").append(webElem.trim()).append("</WBS_ELEM>\n");
            }
            if (idFoncSuppl.trim().length() > 0) {
                sb.append("\t\t\t<ID_FONC_SUPPL txt2xml:TxtValue=\"").append(idFoncSuppl).append("\">").append(idFoncSuppl.trim()).append("</ID_FONC_SUPPL>\n");
            }
            if (grcomptessuppl.trim().length() > 0) {
                sb.append("\t\t\t<GR_COMPTES_SUPPL txt2xml:TxtValue=\"").append(grcomptessuppl).append("\">").append(grcomptessuppl.trim()).append("</GR_COMPTES_SUPPL>\n");
            }
            if (idChourusSuppl.trim().length() > 0) {
                sb.append("\t\t\t<ID_CHOR_SUPPL txt2xml:TxtValue=\"").append(idChourusSuppl).append("\">").append(idChourusSuppl.trim()).append("</ID_CHOR_SUPPL>\n");
            }
            if (funcArea.trim().length() > 0) {
                sb.append("\t\t\t<FUNC_AREA txt2xml:TxtValue=\"").append(funcArea).append("\">").append(funcArea.trim()).append("</FUNC_AREA>\n");
            }

           if (anaMin.trim().length() > 0) {
                sb.append("\t\t\t<ANA_MIN txt2xml:TxtValue=\"").append(anaMin).append("\">").append(anaMin.trim()).append("</ANA_MIN>\n");
            }
  
            if (locMin.trim().length() > 0) {
                sb.append("\t\t\t<LOC_MIN txt2xml:TxtValue=\"").append(locMin).append("\">").append(locMin.trim()).append("</LOC_MIN>\n");
           

            }
            if (natMin.trim().length() > 0) {
                sb.append("\t\t\t<NAT_MIN txt2xml:TxtValue=\"").append(natMin).append("\">").append(natMin.trim()).append("</NAT_MIN>\n");
            }
            
            if (axmin1.trim().length() > 0) {
                sb.append("\t\t\t<AXMIN1 txt2xml:TxtValue=\"").append(axmin1).append("\">").append(axmin1.trim()).append("</AXMIN1>\n");
            }
            if (axmin2.trim().length() > 0) {
            sb.append("\t\t\t<AXMIN2 txt2xml:TxtValue=\"").append(axmin2).append("\">").append(axmin2.trim()).append("</AXMIN2>\n");
            }
        }
        sb.append("\t\t</"+TAG_LIGNE+">\n");
        return sb.toString().getBytes(ENCODING_XML);
    }
    private byte[] makeTranformLineInconnue(String line, int nbLignesParcourues) throws UnsupportedEncodingException {
   	 System.out.println("makeTranformLine : "+line);
        StringBuffer sb = new StringBuffer("\t\t<"+TAG_LIGNE_INCONNUE+" txt2xml:LineTxt=\"" + nbLignesParcourues + "\">\n");
        if (line.trim().length() != 0) {
            sb.append("\t\t\t<LIGNE_INCONNUE txt2xml:TxtValue=\"").append(line).append("\">").append(line.trim()).append("</LIGNE_INCONNUE>\n");
        }
        sb.append("\t\t</"+TAG_LIGNE_INCONNUE+">\n");
        return sb.toString().getBytes(ENCODING_XML);
    }
}
