package com.fitbank.detailmanager;

import com.fitbank.common.Helper;
import com.fitbank.contentsmanager.ManagerUtils;
import java.io.File;
import java.util.prefs.Preferences;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Clob;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import org.apache.commons.io.IOUtils;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;

/**
 * Clase que permite descargar los details procesados en un aplicativo
 * segun la tabla TLOGMENSAJESXML.
 * 
 * @author SoftwareHouse S.A.
 */
public class DetailDownloader {

    private Integer numeroDetails;

    private final Integer cantidad;

    private final String path;

    private final String messageTypes;

    private final String exportTypes;

    private static final String SQL_DETAILS = "SELECT t1.NUMEROMENSAJE, t1.MENSAJEENTRADA FROM TLOGMENSAJES t2 "
            + " JOIN TLOGMENSAJESXML t1 ON t1.NUMEROMENSAJE = t2.NUMEROMENSAJE AND t2.TIPOMENSAJE IN (:messageTypes)"
            + " WHERE ROWNUM <= :rownum";

    public DetailDownloader(String path, String messageTypes, String exportType, Integer cantidad) {
        numeroDetails = 0;
        this.path = path;
        this.messageTypes = messageTypes;
        this.exportTypes = exportType;
        this.cantidad = cantidad;
    }

    public void process() {
        try {
            ManagerUtils.openSession();
            this.getBlobsLogMensajesXml();
        } catch (Exception e) {
            System.out.println("Error al descargar : " + e.toString());
        }
        System.out.println(
                "######################################################################");
        System.out.println("Numero total de Details descargados "
                + numeroDetails);
        System.out.println(
                "######################################################################");
    }

    private void getBlobsLogMensajesXml() {
        try {
            SQLQuery query = Helper.createSQLQuery(DetailDownloader.SQL_DETAILS);
            query.setParameterList("messageTypes", messageTypes.split(","));
            query.setInteger("rownum", cantidad);

            ScrollableResults rs = query.scroll();
            PrintStream out = new PrintStream(new File(this.path + "details.txt"));

            while (rs.next()) {
                String name = (String) rs.get(0);
                System.out.println("Descargando Detail " + name + "...");
                Clob detail = (Clob) rs.get(1);
                Integer detailLength = Integer.valueOf(String.valueOf(detail.length()));

                if (this.exportTypes.contains("Un solo")) {
                    out.println(detail.getSubString(1, detailLength));
                }
                if (this.exportTypes.contains("Varios")) {
                    IOUtils.write(detail.getSubString(1, detailLength), 
                            new FileOutputStream(this.path + "detail" + 
                            numeroDetails + ".xml"), "UTF-8");
                }
                System.out.println("\tSe descargó correctamente");
                numeroDetails++;
            }

            rs.close();
            out.close();
        } catch (Exception e) {
            System.out.println("Error al guardar el detail : " + e.toString());
        }
    }

    public static void main(String args[])
            throws com.FitBank.xml.Parser.ExcepcionParser {
        Preferences preferences = Preferences.userNodeForPackage(
                DetailDownloader.class);
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        String directorioAnterior = preferences.get("destino", "");
        jfc.setDialogTitle("Directorio destino");
        jfc.setSelectedFile(new File(directorioAnterior));

        if (jfc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
            System.exit(0);
        }

        JCheckBox chxCon = new JCheckBox("CON");
        JCheckBox chxMan = new JCheckBox("MAN");
        JCheckBox chxRep = new JCheckBox("REP");
        JCheckBox chxSig = new JCheckBox("SIG");
        JCheckBox chxLot = new JCheckBox("LOT");
        JCheckBox chxBat = new JCheckBox("BAT");
        JCheckBox chxFrm = new JCheckBox("FRM");
        JCheckBox[] params = new JCheckBox[] {chxCon, chxMan, chxRep, chxSig, chxLot, chxBat, chxFrm};
        JOptionPane.showConfirmDialog(
                null,
                params,
                "Seleccione el tipo de Mensaje",
                JOptionPane.DEFAULT_OPTION);

        String tipoMensajes = "";
        boolean first = true;
        for (JCheckBox checkBox : params) {
            if (checkBox.isSelected()) {
                if (!first) {
                    tipoMensajes = tipoMensajes.concat(",");
                } else {
                    first = false;
                }
                tipoMensajes = tipoMensajes.concat(checkBox.getText());
            }
        }

        JCheckBox chxSingle = new JCheckBox("Un solo archivo");
        JCheckBox chxMultiple = new JCheckBox("Varios archivos");
        params = new JCheckBox[] {chxSingle, chxMultiple};
        JOptionPane.showConfirmDialog(null,
                params,
                "Seleccione el tipo de Salida",
                JOptionPane.DEFAULT_OPTION);

        String tiposExport = "";
        first = true;
        for (JCheckBox checkBox : params) {
            if (checkBox.isSelected()) {
                if (!first) {
                    tiposExport = tiposExport.concat(",");
                } else {
                    first = false;
                }
                tiposExport = tiposExport.concat(checkBox.getText());
            }
        }

        Integer cantidad = Integer.valueOf(JOptionPane.showInputDialog(null,
                new Object[]{new JLabel("Escriba el numero de details a descargar")},
                "Cantidad de Details a descargar",
                JOptionPane.DEFAULT_OPTION));
        String directorio = jfc.getSelectedFile().getPath() + "/";
        DetailDownloader dd = new DetailDownloader(directorio, tipoMensajes, 
                tiposExport, cantidad);
        dd.process();
    }

}
