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

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 DpDirecteTxt2Xml extends AbstractTxt2Xml implements Txt2Xml {

	private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(DpDirecteTxt2Xml.class);
	
	private final static String ENCODING_TXT = "UTF-8";
	private final static String ENCODING_XML = "UTF-8";
	
	private final static int LENGTH_ENTETE = 808;
	private final static int LENGTH_LINE = 619;
		
	public DpDirecteTxt2Xml() {
		super();
	}
/*
	public static void main(final String[] args) {
		DpDirecteTxt2Xml thisDP = new DpDirecteTxt2Xml();
		thisDP.transform(new File("C:/TEMP/AIFE/FEN0029A/FEN0029A_SIS001_SIS001002900151"));
	}
*/	
	public File transform(File f) {
		File ret=null;
		try {
			if(isXmlFile(f,ENCODING_TXT)){
				ret = f;
			} else {
				ret = makeTransformDpDirecte(f);
			}
		} catch (Exception e) {
			logger.debug("Problème de transformation du flux !", e);
		}
		return ret;
	}

	/**
	 * @param f
	 * @return
	 * @throws IOException
	 */
	private File makeTransformDpDirecte(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<FEN0029A xmlns=\"http://www.xemelios.org/namespaces#FEN0029A\" 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));
					}
				}
				line=br.readLine();
			}
			fos.write("\t</DP_DIRECTE>\n</FEN0029A>".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</DP_DIRECTE>\n\t<DP_DIRECTE>\n\t\t<ENTETE txt2xml:LineTxt=\""+nbLignesParcourues+"\">\n");
		} else {
			sb = new StringBuffer("\t<DP_DIRECTE>\n\t\t<ENTETE txt2xml:LineTxt=\""+nbLignesParcourues+"\">\n");
		}
		/* Compris entre LENGTH_ENTETE-2 && LENGTH_ENTETE */
		if(line.length() >= (LENGTH_ENTETE-2) && line.length() <= LENGTH_ENTETE){
			/* Variables à récupérer
			 * 		Lot3 - Format pivot AE FEN0029A - Réception des demandes de paiement directes V2.2.doc
			 */
			try{
				String idAe = line.substring(1, 13);
				String codeAppli = line.substring(13, 19);
				String typeDp = line.substring(19, 21);
				String initiateur = line.substring(21, 33);
				String refDocNoFour = line.substring(33, 58);
				String description = line.substring(58, 108);
				String docDate = line.substring(108, 116);
				String busArea = line.substring(116, 120);
				String compCode = line.substring(120, 124);
				String typeTiers = line.substring(124, 128);
				String idFoncTiers = line.substring(128, 208);
				String idChorusTiers = line.substring(208, 218);
				String name1 = line.substring(218, 253);
				String name2 = line.substring(253, 288);
				String name3 = line.substring(288, 323);
				String name4 = line.substring(323, 358);
				String cp = line.substring(358, 368);
				String city = line.substring(368, 403);
				String country = line.substring(403, 405);
				String street = line.substring(405, 440);
				String siretCpd = line.substring(440, 454);
				String codeIban = line.substring(454, 488);
				String bankAcct = line.substring(488, 506);
				String bankNo = line.substring(506, 521);
				String bankCtry = line.substring(521, 523);
				String ctrlKey = line.substring(523, 525);
				String baseDate = line.substring(525, 533);
				String pmntTrms = line.substring(523, 527);
				String pmntMeth = line.substring(527, 538);
				String currency = line.substring(538, 541);
				String delaiBr = line.substring(541, 545);
				String raisonBr = line.substring(545, 547);
				String recepDateBr = line.substring(547, 555);
				String codeInterets = line.substring(555, 557);
				String filler250 = line.substring(557, 807);
			
				sb.append("\t\t\t<ID_AE txt2xml:TxtValue=\"").append(idAe).append("\">").append(idAe.trim()).append("</ID_AE>\n");
				sb.append("\t\t\t<CODE_APPLI txt2xml:TxtValue=\"").append(codeAppli).append("\">").append(codeAppli.trim()).append("</CODE_APPLI>\n");
				sb.append("\t\t\t<TYPE_DP txt2xml:TxtValue=\"").append(typeDp).append("\">").append(typeDp.trim()).append("</TYPE_DP>\n");
				sb.append("\t\t\t<INITIATEUR txt2xml:TxtValue=\"").append(initiateur).append("\">").append(initiateur.trim()).append("</INITIATEUR>\n");
				sb.append("\t\t\t<REF_DOC_NO_FOUR txt2xml:TxtValue=\"").append(refDocNoFour).append("\">").append(refDocNoFour.trim()).append("</REF_DOC_NO_FOUR>\n");
				sb.append("\t\t\t<DESCRIPTION txt2xml:TxtValue=\"").append(description).append("\">").append(description.trim()).append("</DESCRIPTION>\n");
				sb.append("\t\t\t<DOC_DATE txt2xml:TxtValue=\"").append(docDate).append("\">").append(docDate.trim()).append("</DOC_DATE>\n");
				sb.append("\t\t\t<BUS_AREA txt2xml:TxtValue=\"").append(busArea).append("\">").append(busArea.trim()).append("</BUS_AREA>\n");
				sb.append("\t\t\t<COMP_CODE txt2xml:TxtValue=\"").append(compCode).append("\">").append(compCode.trim()).append("</COMP_CODE>\n");
				sb.append("\t\t\t<TYPE_TIERS txt2xml:TxtValue=\"").append(typeTiers).append("\">").append(typeTiers.trim()).append("</TYPE_TIERS>\n");
				sb.append("\t\t\t<ID_FONCT_TIERS txt2xml:TxtValue=\"").append(idFoncTiers).append("\">").append(idFoncTiers.trim()).append("</ID_FONCT_TIERS>\n");
				sb.append("\t\t\t<ID_CHORUS_TIERS txt2xml:TxtValue=\"").append(idChorusTiers).append("\">").append(idChorusTiers.trim()).append("</ID_CHORUS_TIERS>\n");
				sb.append("\t\t\t<NAME1 txt2xml:TxtValue=\"").append(name1).append("\">").append(name1.trim()).append("</NAME1>\n");
				sb.append("\t\t\t<NAME2 txt2xml:TxtValue=\"").append(name2).append("\">").append(name2.trim()).append("</NAME2>\n");
				sb.append("\t\t\t<NAME3 txt2xml:TxtValue=\"").append(name3).append("\">").append(name3.trim()).append("</NAME3>\n");
				sb.append("\t\t\t<NAME4 txt2xml:TxtValue=\"").append(name4).append("\">").append(name4.trim()).append("</NAME4>\n");
				sb.append("\t\t\t<CP txt2xml:TxtValue=\"").append(cp).append("\">").append(cp.trim()).append("</CP>\n");
				sb.append("\t\t\t<CITY txt2xml:TxtValue=\"").append(city).append("\">").append(city.trim()).append("</CITY>\n");
				sb.append("\t\t\t<COUNTRY txt2xml:TxtValue=\"").append(country).append("\">").append(country.trim()).append("</COUNTRY>\n");
				sb.append("\t\t\t<STREET txt2xml:TxtValue=\"").append(street).append("\">").append(street.trim()).append("</STREET>\n");
				sb.append("\t\t\t<SIRET_CPD txt2xml:TxtValue=\"").append(siretCpd).append("\">").append(siretCpd.trim()).append("</SIRET_CPD>\n");
				sb.append("\t\t\t<CODE_IBAN txt2xml:TxtValue=\"").append(codeIban).append("\">").append(codeIban.trim()).append("</CODE_IBAN>\n");
				sb.append("\t\t\t<BANK_ACCT txt2xml:TxtValue=\"").append(bankAcct).append("\">").append(bankAcct.trim()).append("</BANK_ACCT>\n");
				sb.append("\t\t\t<BANK_NO txt2xml:TxtValue=\"").append(bankNo).append("\">").append(bankNo.trim()).append("</BANK_NO>\n");
				sb.append("\t\t\t<BANK_CTRY txt2xml:TxtValue=\"").append(bankCtry).append("\">").append(bankCtry.trim()).append("</BANK_CTRY>\n");
				sb.append("\t\t\t<CTRL_KEY txt2xml:TxtValue=\"").append(ctrlKey).append("\">").append(ctrlKey.trim()).append("</CTRL_KEY>\n");
				sb.append("\t\t\t<BASE_DATE txt2xml:TxtValue=\"").append(baseDate).append("\">").append(baseDate.trim()).append("</BASE_DATE>\n");
				sb.append("\t\t\t<PMNTTRMS txt2xml:TxtValue=\"").append(pmntTrms).append("\">").append(pmntTrms.trim()).append("</PMNTTRMS>\n");
				sb.append("\t\t\t<PYMT_METH txt2xml:TxtValue=\"").append(pmntMeth).append("\">").append(pmntMeth.trim()).append("</PYMT_METH>\n");
				sb.append("\t\t\t<CURRENCY txt2xml:TxtValue=\"").append(currency).append("\">").append(currency.trim()).append("</CURRENCY>\n");
				sb.append("\t\t\t<DELAI_BR txt2xml:TxtValue=\"").append(delaiBr).append("\">").append(delaiBr.trim()).append("</DELAI_BR>\n");
				sb.append("\t\t\t<RAISON_BR txt2xml:TxtValue=\"").append(raisonBr).append("\">").append(raisonBr.trim()).append("</RAISON_BR>\n");
				sb.append("\t\t\t<RECEPT_DATE_BR txt2xml:TxtValue=\"").append(recepDateBr).append("\">").append(recepDateBr.trim()).append("</RECEPT_DATE_BR>\n");
				sb.append("\t\t\t<CODE_INTERETS txt2xml:TxtValue=\"").append(codeInterets).append("\">").append(codeInterets.trim()).append("</CODE_INTERETS>\n");
				sb.append("\t\t\t<FILLER250 txt2xml:TxtValue=\"").append(filler250).append("\">").append(filler250.trim()).append("</FILLER250>\n");
			}catch (Exception e) {
				System.out.println("ENTETE : Erreur de transfmormation : "+line);
			}
		}
		sb.append("\t\t</ENTETE>\n");
		return sb.toString().getBytes(ENCODING_XML);
	}
	
	private byte[] makeTranformLine(String line, int nbLignesParcourues) throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer("\t\t<LIGNE_CHARGE txt2xml:LineTxt=\""+nbLignesParcourues+"\">\n");
		if(line.length() >= (LENGTH_LINE-2) && line.length() <= LENGTH_LINE){
			String idAe = line.substring(1, 13);
			String numLigne = line.substring(13, 19);
			String glAccount = line.substring(19, 29);
			String itemText = line.substring(29, 79);
			String taxCode = line.substring(79, 81);
			String wbsElemE = line.substring(81, 105);
			String costcenter = line.substring(105, 115);
			String fund = line.substring(115, 125);
			String fundsCtr = line.substring(125, 141);
			String fundsArea = line.substring(141, 157);
			String activite = line.substring(157, 181);
			String tFonc = line.substring(181, 205);
			String projAnaMinist = line.substring(205, 227);
			String localMinist = line.substring(227, 249);
			String localInterMinist = line.substring(249, 257);
			String natureMinist = line.substring(257, 268);
			String cper = line.substring(268, 283);
			String presage = line.substring(283, 298);
			String axe1 = line.substring(298, 320);
			String axe2 = line.substring(320, 342);
			String montant = line.substring(342, 367);
			String filler250 = line.substring(368, 617);
			
			sb.append("\t\t\t<ID_AE txt2xml:TxtValue=\"").append(idAe).append("\">").append(idAe.trim()).append("</ID_AE>\n");
			sb.append("\t\t\t<NUM_LIGNE txt2xml:TxtValue=\"").append(numLigne).append("\">").append(numLigne.trim()).append("</NUM_LIGNE>\n");
			sb.append("\t\t\t<GL_ACCOUNT txt2xml:TxtValue=\"").append(glAccount).append("\">").append(glAccount.trim()).append("</GL_ACCOUNT>\n");
			sb.append("\t\t\t<ITEM_TEXT txt2xml:TxtValue=\"").append(itemText).append("\">").append(itemText.trim()).append("</ITEM_TEXT>\n");
			sb.append("\t\t\t<TAX_CODE txt2xml:TxtValue=\"").append(taxCode).append("\">").append(taxCode.trim()).append("</TAX_CODE>\n");
			sb.append("\t\t\t<WBS_ELEM_E txt2xml:TxtValue=\"").append(wbsElemE).append("\">").append(wbsElemE.trim()).append("</WBS_ELEM_E>\n");
			sb.append("\t\t\t<COSTCENTER txt2xml:TxtValue=\"").append(costcenter).append("\">").append(costcenter.trim()).append("</COSTCENTER>\n");
			sb.append("\t\t\t<FUND txt2xml:TxtValue=\"").append(fund).append("\">").append(fund.trim()).append("</FUND>\n");
			sb.append("\t\t\t<FUNDS_CTR txt2xml:TxtValue=\"").append(fundsCtr).append("\">").append(fundsCtr.trim()).append("</FUNDS_CTR>\n");
			sb.append("\t\t\t<FUNC_AREA txt2xml:TxtValue=\"").append(fundsArea).append("\">").append(fundsArea.trim()).append("</FUNC_AREA>\n");
			sb.append("\t\t\t<ACTIVITE txt2xml:TxtValue=\"").append(activite).append("\">").append(activite.trim()).append("</ACTIVITE>\n");
			sb.append("\t\t\t<T_FONC txt2xml:TxtValue=\"").append(tFonc).append("\">").append(tFonc.trim()).append("</T_FONC>\n");
			sb.append("\t\t\t<PROJ_ANA_MINIST txt2xml:TxtValue=\"").append(projAnaMinist).append("\">").append(projAnaMinist.trim()).append("</PROJ_ANA_MINIST>\n");
			sb.append("\t\t\t<LOCAL_MINIST txt2xml:TxtValue=\"").append(localMinist).append("\">").append(localMinist.trim()).append("</LOCAL_MINIST>\n");
			sb.append("\t\t\t<LOCAL_INTER_MINIST txt2xml:TxtValue=\"").append(localInterMinist).append("\">").append(localInterMinist.trim()).append("</LOCAL_INTER_MINIST>\n");
			sb.append("\t\t\t<NATURE_MINIST txt2xml:TxtValue=\"").append(natureMinist).append("\">").append(natureMinist.trim()).append("</NATURE_MINIST>\n");
			sb.append("\t\t\t<CPER txt2xml:TxtValue=\"").append(cper).append("\">").append(cper.trim()).append("</CPER>\n");
			sb.append("\t\t\t<PRESAGE txt2xml:TxtValue=\"").append(presage).append("\">").append(presage.trim()).append("</PRESAGE>\n");
			sb.append("\t\t\t<AXE_1 txt2xml:TxtValue=\"").append(axe1).append("\">").append(axe1.trim()).append("</AXE_1>\n");
			sb.append("\t\t\t<AXE_2 txt2xml:TxtValue=\"").append(axe2).append("\">").append(axe2.trim()).append("</AXE_2>\n");
			sb.append("\t\t\t<MONTANT txt2xml:TxtValue=\"").append(montant).append("\">").append(getAmount(montant.trim())).append("</MONTANT>\n");
			sb.append("\t\t\t<FILLER250 txt2xml:TxtValue=\"").append(filler250).append("\">").append(filler250.trim()).append("</FILLER250>\n");
		}
		sb.append("\t\t</LIGNE_CHARGE>\n");
		return sb.toString().getBytes(ENCODING_XML);
	}
}
