/*
 * MIT License
 *
 * Copyright (c) 2018-2019 Daniel Cortes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package danielcortes.xyz.controllers;

import danielcortes.xyz.informes.InformeEgresos;
import danielcortes.xyz.informes.InformeLibroDeVentas;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import danielcortes.xyz.utils.FileUtils;
import danielcortes.xyz.utils.StringUtils;
import danielcortes.xyz.views.MonthSelectDialog;
import danielcortes.xyz.views.InformesView;
import danielcortes.xyz.views.TipoEgresoSelectDialog;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class InformesController {
    private InformesView view;

    public InformesController(InformesView view) {
        this.view = view;
        this.setupViewEvents();
    }

    private void setupViewEvents() {
        this.view.getInformeLibroDeVentasButton().addActionListener(e -> generarInformeLibroDeVentasListener());
        this.view.getGenerarEgresosFacturasMateriaPrimaButton().addActionListener(e -> generarInformeEgresosListener());
    }

    private void generarInformeLibroDeVentasListener() {
        LocalDate month = askForMonth();
        if (month == null) {
            return;
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM YYYY");
        String formatedName = month.format(formatter);
        String capitalized = StringUtils.toUpperCase(formatedName);

        File saveFile = askForFile("Libro " + capitalized);
        if (saveFile == null) {
            return;
        }

        InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile);
        File generatedFile = informe.generarInforme();

        this.showConfirmation(generatedFile);
    }

    private void generarInformeEgresosListener() {
        TipoEgreso tipoEgreso = askForTipoEgreso();
        if (tipoEgreso == null) {
            return;
        }

        LocalDate month = askForMonth();
        if (month == null) {
            return;
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM YYYY");
        String formatedMonth = month.format(formatter);

        File saveFile = askForFile("Informe Egresos - " + tipoEgreso.getNombre() + " - " + StringUtils.toUpperCase(formatedMonth));
        if (saveFile == null) {
            return;
        }

        InformeEgresos informe = new InformeEgresos(tipoEgreso.getId(), month, saveFile);
        File generatedFile = informe.generarInforme();

        this.showConfirmation(generatedFile);
    }

    private LocalDate askForMonth() {
        MonthSelectDialog monthSelectDialog = new MonthSelectDialog(this.view.getContentPanel());
        if (monthSelectDialog.isAcepted()) {
            return monthSelectDialog.getMonth();
        } else {
            return null;
        }
    }

    private TipoEgreso askForTipoEgreso() {
        TipoEgresoSelectDialog tipoEgresoSelectDialog = new TipoEgresoSelectDialog(this.view.getContentPanel());
        if (tipoEgresoSelectDialog.isAcepted()) {
            return tipoEgresoSelectDialog.getTipoEgreso();
        } else {
            return null;
        }
    }

    private File askForFile(String suggestedName) {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        chooser.setSelectedFile(new File(suggestedName + ".xls"));
        chooser.setFileFilter(new FileNameExtensionFilter("Excel 2007", "xls"));

        if (chooser.showSaveDialog(this.view.getContentPanel()) == JFileChooser.APPROVE_OPTION) {
            String filename = chooser.getSelectedFile().toString();
            if (FileUtils.isValidPath(filename)) {
                JOptionPane.showMessageDialog(this.view.getContentPanel(),"El archivo seleccionado no es valido","Archivo no valido", JOptionPane.ERROR_MESSAGE);
                return null;
            } else if (!filename.endsWith(".xls")) {
                filename += ".xls";
            }

            return new File(filename);
        } else {
            return null;
        }
    }

    private void showConfirmation(File file) {
        int result = JOptionPane.showConfirmDialog(
                this.view.getContentPanel(),
                "El informes se a generado\n" +
                        "¿Desea abrirlo?",
                "Confirmacion",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE
        );
        if (result == 0) {
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
