package com.fitbank.report;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import java.util.ResourceBundle;

import org.xml.sax.InputSource;

import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory;
import net.sf.jasperreports.engine.util.JRXmlUtils;

import com.fitbank.common.FileHelper;
import com.fitbank.common.helper.XMLParser;
import com.fitbank.dto.management.Detail;
import com.fitbank.homebanking.HBParam;

public class Report {
   private Detail detail;
   private String path;
   private ReportTypes type;
   private String xml;
   
   public Report(Detail pDetail,String pPath,ReportTypes pType, String xml) throws Exception{
  	 detail=pDetail;
  	 this.path=pPath;
  	 this.type=pType;
  	 this.xml=xml;
   }
   
    public void executeReport(OutputStream pOut) throws Exception{
        InputStream report=this.getReport();
        try{
            ReportManager rm=new ReportManager(report,pOut,type);
            rm.putParameter("path", this.path);
                        
            rm.putParameter("logo",HBParam.getInstance().getStringValue("report.header.logo"));  
            rm.putParameter(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, JRXmlUtils.parse(new InputSource(new java.io.StringReader(this.xml))));
            rm.putParameter("detail", detail);
            //rm.putParameter(JRParameter.REPORT_LOCALE,new Locale(this.detail.getLanguage().toLowerCase()));
            rm.putParameter(JRParameter.REPORT_RESOURCE_BUNDLE,ResourceBundle.getBundle("i18n", new Locale(this.detail.getLanguage().toLowerCase())));
            rm.evalReport();
        }finally{
            report.close();
        }
    }
    
   private InputStream getReport() throws Exception{
       String reportName = (String)detail.findFieldByNameCreate("_REPORT").getValue();
       if(reportName==null || reportName.compareTo("")==0){
           reportName = "R"+detail.getSubsystem()+detail.getTransaction()+detail.getVersion();  
       }
       InputStream in=new FileInputStream(path+"/"+reportName+".jasper");   
       return in;
   }
   
   public static void main(String[] args) {
		try {
			FileOutputStream fout=new FileOutputStream("/logs/a.xls");
			try{
				String data = FileHelper.readFile( "/home/gfiallos/public/rs.xml");
				XMLParser xml = new XMLParser(data);
				Detail detail = new Detail(xml);
				Report rep=new Report(detail,"/app/iReport-2.0.5/bin",ReportTypes.PDF, detail.toXml());
				rep.executeReport(fout);
			}finally{
				fout.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
