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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;

public class AbstractTxt2Xml {	
	private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(AbstractTxt2Xml.class);
	
	private static final DecimalFormat df = new DecimalFormat("##0.0000");
	
	public AbstractTxt2Xml(){
		super();
	}
	
	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 && i>=1) {				
				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 String getAmount(String montant){
		Double mt= 0d;
        try {
        	if(montant.trim().length() > 0){
        		mt = Double.parseDouble(montant);
        	}
        	return df.format(mt/100d);
        } catch(NumberFormatException ex) {
        	logger.debug("Problème lors du formattage du montant ("+montant+") : "+ex.getLocalizedMessage());
        }
        return montant;
	}
	
	/**
	 * 
	 * @param date : frmat AAAAMMJJ
	 * @return
	 */
	public String getDateLong(String date){
		if(date.length()==8){
			String annee = date.substring(0, 4);
			String mois = date.substring(4, 6);
			String jour = date.substring(6, 8);
			return new StringBuffer(annee).append("-").append(mois).append("-").append(jour).toString();
		} else {
			logger.debug("Problème lors du formattage de la date ("+date+") ");
		}
		return date;
	}
}
