/*
 * 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.data.Configuration;
import danielcortes.xyz.informes.InformeEgresos;
import danielcortes.xyz.informes.InformeLibroDeVentas;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import danielcortes.xyz.utils.StringUtils;
import danielcortes.xyz.views.EstadoResultadoView;
import danielcortes.xyz.views.InformesView;
import danielcortes.xyz.views.dialogs.MonthSelectDialog;
import danielcortes.xyz.views.dialogs.TipoEgresoSelectDialog;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
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());
        this.view.getEstadoResultadoButton().addActionListener(e -> {
            EstadoResultadoView view = new EstadoResultadoView();
            EstadoResultadoController controller = new EstadoResultadoController(view);

            JFrame frame = new JFrame("Estado Resultado"+ ": " + Configuration.get("nombre_caja"));
            frame.setContentPane(view.getContentPanel());
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(1000,600);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

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

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

        Path saveFile = askForFile(Configuration.get("base_save_directory") + "Libro " + capitalized);
        if (saveFile == null) {
            return;
        }

        InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile);
        Path 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);

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

        InformeEgresos informe = new InformeEgresos(tipoEgreso.getId(), month, saveFile);
        Path 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 Path 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) {
            return processFilePath(chooser.getSelectedFile().getPath());


        } else {
            return null;
        }
    }

    private void showConfirmation(Path path) {
        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(path.toFile());
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private Path processFilePath(String pathString) {
        Path path;

        if (!pathString.endsWith(".xls")) {
            pathString = pathString + ".xls";
        }

        try {
            path = Paths.get(pathString);
        } catch (InvalidPathException e) {
            e.printStackTrace();

            JOptionPane.showMessageDialog(
                    this.view.getContentPanel(),
                    "El nombre de archivo entregado es invalido",
                    "Error!",
                    JOptionPane.ERROR_MESSAGE
            );
            return null;
        }

        try {
            Files.createFile(path);
        } catch (FileAlreadyExistsException e) {
            int response = JOptionPane.showConfirmDialog(
                    this.view.getContentPanel(),
                    "El archivo ya existe\n¿Desea sobreescribirlo?",
                    "Confirmacion",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE
            );

            if (response != 0) {
                return null;
            }

        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    this.view.getContentPanel(),
                    "No a sido posible crear el archivo",
                    "Error!",
                    JOptionPane.ERROR_MESSAGE
            );

            return null;
        }

        return path;
    }
}
