package com.fitbank.servlet;

import com.fitbank.common.Helper;
import com.fitbank.common.helper.XMLParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fitbank.dto.management.Detail;
import com.fitbank.dto.management.Table;
import com.fitbank.homebanking.DataManage;
import com.fitbank.report.Report;
import com.fitbank.report.ReportTypes;


public class JSFServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String path;

    @Override
    public void init(ServletConfig config) throws ServletException {
        path = config.getServletContext().getRealPath("/") + "/rep";
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //FIXME no trabaja con IE
        //resp.setHeader("Pragma", "no-cache");
        //resp.setHeader("Cache-Control","no-cache");
        OutputStream os = resp.getOutputStream();
        try {
            String type = req.getParameter("type");
            if (type == null) {
                type = "PDF";
            }
            ReportTypes rType = ReportTypes.valueOf(type.toUpperCase());
            resp.setContentType(rType.getContentType());
            resp.flushBuffer();
            resp.setStatus(HttpServletResponse.SC_RESET_CONTENT);

            //DataManage dm = (DataManage) req.getSession().getAttribute(DataManage.KEY);
            Detail detail = (Detail)req.getSession().getAttribute("repDetail"); //dm.get(req.getParameter("report"));
            if(detail.getSubsystem()!=null && detail.getTransaction()!=null){
                if (detail.getSubsystem().compareTo("18") == 0 && detail.getTransaction().compareTo("4000") == 0) {
                    detail = this.ordenarDetail(detail);
                }
            }
            Report rep = new Report(detail, path, rType, detail.toXml());

            File f = new File(path + "/print/" + detail.getMessageid());
            f.createNewFile();
            String file = path + "/print/" + detail.getMessageid();
            FileOutputStream out = new FileOutputStream(file);
            rep.executeReport(out);
            out.close();
            FileInputStream fis = new FileInputStream(file);
            byte b[] = new byte[9999];
            int car = 0;
            do {
                car = fis.read(b);
                if (car > 0) {
                    os.write(b, 0, car);
                }
            } while (car > 0);
            fis.close();
            //f.delete();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        } finally {
            os.close();
        }
    }

    public String getDetailKey(HttpServletRequest req) {
        String key = null;
        if (key == null) {
            key = DataManage.DETAIL_KEY;
            String paramKey = req.getParameter("_detail_");
            if (paramKey != null && paramKey.compareTo("") != 0) {
                key = paramKey;
            } else {
                paramKey = (String)req.getSession().getAttribute("_detail_");
                // this.getSession().setAttribute("_detail_","");
                if (paramKey != null && paramKey.compareTo("") != 0) {
                    key = paramKey;
                }
            }
        }
        return key;
    }

    /** Caso especial para reporte de Posicion Consolidada */
    public Detail ordenarDetail(Detail detail) throws Exception {
        try {
            XMLParser xml = new XMLParser(detail.toXml());
            Detail ordDetail = new Detail(xml);
            ordDetail.removeTables();
            Table t = detail.findTableByAlias("AHORROS");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("CORRIENTES");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("CTS");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("PLAZO");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("TARJETACREDITO");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("PRESTAMOS");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("LETRADESCONTADA");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("LETRACOBRANZAORDINARIA");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("LETRACOBRANZAGARANTIA");
            ordDetail.addTable(t);
            t = detail.findTableByAlias("TIPOLETRAS");
            ordDetail.addTable(t);
            return ordDetail;
        } catch (Exception e) {
            Helper.closeAuxiliarSession();
            throw e;
        }
    }
}