package com.fitbank.reportmanager;

import com.fitbank.common.Helper;
import com.fitbank.contentsmanager.ManagerUtils;
import com.fitbank.dto.management.Detail;
import com.fitbank.security.util.UploadFiles;
import com.fitbank.util.Debug;
import com.fitbank.util.ListaArchivos;
import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
import org.apache.commons.io.IOUtils;

/**
 * Clase que permite subir reportes a la base de datos independientemente
 * del servidor de aplicaciones.
 * 
 * @author SoftwareHouse S.A.
 */
public class ReportUploader {

    private final UploadFiles uf = new UploadFiles();

    private static final List<String> siSubidos = new LinkedList<String>();

    private static final List<String> noSubidos = new LinkedList<String>();

    private String language;

    private Integer company;

    private String description = "Uploaded by ReportUploader";

    public ReportUploader(Integer company, String language) {
        this.company = company;
        this.language = language;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getCompany() {
        return company;
    }

    public void setCompany(Integer cia) {
        this.company = cia;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getLanguage() {
        return this.language;
    }

    public void process(File[] files, boolean first) {
        try {
            if (first) {
                ManagerUtils.openSession();
                Detail pDetail = new Detail();
                pDetail.setCompany(this.getCompany());
                uf.initParameters(pDetail);
            }

            for (File file : files) {
                try {
                    if (file.isDirectory()) {
                            this.process(file.listFiles(), false);
                    } else {
                        String name = file.getName();
                        String tipo = name.substring(name.lastIndexOf('.') + 1);

                        if ("jasper".equals(tipo) || "jrxml".equals(tipo)) {
                            Helper.beginTransaction();
                            System.out.println("Procesando " + name + "...");
                            byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
                            uf.setNombre(name.substring(0, name.indexOf('.')));
                            uf.setLanguage(this.getLanguage());
                            uf.executeUpload(bytes, tipo);
                            Helper.commitTransaction();
                            siSubidos.add(name);
                            System.out.println("Subido exitosamente!\n");
                        }
                    }
                } catch (Exception e) {
                    Helper.rollbackTransaction();
                    noSubidos.add(file.getName());
                    System.out.println("Errores al subir...:");
                    Debug.error(e.getMessage() + "\n");
                }
            }
        } catch (Exception e) {
            Debug.error("Error al procesar reportes", e);
        } finally {
            Helper.closeSession();
        }
        this.printSummary();
    }

    private void printSummary() {
        System.out.println("########################################");
        System.out.println("Reportes subidos: " + siSubidos.size());
        System.out.println("Reportes no subidos: " + noSubidos.size());
        System.out.println("########################################");
        System.out.println("SUBIDOS\t\t\t\tNO SUBIDOS");
        for (int i = 0; i < Math.max(siSubidos.size(), noSubidos.size()); i++) {
            System.out.println((siSubidos.size() > i ? siSubidos.get(i) : "")
                    + "\t\t\t\t" + (noSubidos.size() > i ? noSubidos.get(i) : ""));
        }
    }

    public static void main(String args[]) throws Exception {
        Collection<File> files = ListaArchivos.getLista(ReportUploader.class,
                "jasper", "jrxml");

        Integer company = (Integer) JOptionPane.showInputDialog(null, "Compania",
                "Ingrese el codigo de compania",
                JOptionPane.QUESTION_MESSAGE, null, new Integer[]{2, 3,
                    4, 5, 6, 7, 8, 9, 10}, 0);

        String language = (String) JOptionPane.showInputDialog(null,
                "Idioma",
                "Ingrese el idioma de los reportes",
                JOptionPane.QUESTION_MESSAGE, null, new String[]{
                    "ES", "EN", "IT", "FR",
                    "SW", "IN", "LT", "EB", "CH", "JP"}, 0);

        ReportUploader ru = new ReportUploader(company, language);
        ru.process(files.toArray(new File[0x0]), true);
    }

}
