package com.fitbank.classmanager;

import com.fitbank.common.Helper;
import com.fitbank.contentsmanager.ManagerUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Timestamp;
import java.util.prefs.Preferences;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.apache.commons.io.IOUtils;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;

/**
 * Clase que permite descargar objetos (.class) de la base de datos.
 * 
 * @author SoftwareHouse S.A.
 */
public class ClassDownloader {

    private Integer numeroClases;

    private final String path;

    private final String commandTypes;

    private static final String SQL_CLASSES = "SELECT COMANDO, CLASE "
            + "FROM TFORMATOCOMANDOS WHERE FHASTA=:fhasta AND TIPOCOMANDO IN (:commandTypes)";

    public ClassDownloader(String path, String messageTypes) {
        numeroClases = 0;
        this.path = path;
        this.commandTypes = messageTypes;
    }

    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 Clases descargadas "
                + numeroClases);
        System.out.println(
                "######################################################################");
    }

    private void getBlobsLogMensajesXml() {
        try {
            Timestamp expire = Timestamp.valueOf("2999-12-31 00:00:00");
            SQLQuery query = Helper.createSQLQuery(ClassDownloader.SQL_CLASSES);
            query.setTimestamp("fhasta", expire);
            query.setParameterList("commandTypes", commandTypes.split(","));

            ScrollableResults rs = query.scroll();

            while (rs.next()) {
                String name = ((String) rs.get(0)).replace('.', '/');
                String className = name.substring(name.lastIndexOf('/') + 1) + ".class";
                String classPath = name.substring(0, name.lastIndexOf('/'));
                File filePath = new File(this.path + classPath);
                filePath.mkdirs();
                File fileName = new File(filePath.getAbsolutePath() + "/" + className);
                System.out.println("Descargando clase " + name + "...");
                IOUtils.write(IOUtils.toByteArray(((Blob) rs.get(1)).getBinaryStream()), 
                        new FileOutputStream(fileName));
                System.out.println("\tSe descargó correctamente");
                numeroClases++;
            }

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

    public static void main(String args[])
            throws com.FitBank.xml.Parser.ExcepcionParser {
        Preferences preferences = Preferences.userNodeForPackage(
                ClassDownloader.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[] params = new JCheckBox[] {chxCon, chxMan, chxRep, chxSig, chxLot, chxBat};
        JOptionPane.showConfirmDialog(
                null,
                params,
                "Seleccione el tipo de Comando",
                JOptionPane.DEFAULT_OPTION);

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

        String directorio = jfc.getSelectedFile().getPath() + "/";
        ClassDownloader cd = new ClassDownloader(directorio, tipoComandos);
        cd.process();
    }

}
