/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.ctecinf.view;

/**
 * Os pacotes 'br.com.ctecinf.CTecInf' e 'br.com.ctecinf.text.*' se encontram no
 * site http://ctecinf.com.br/code
 */
import br.com.ctecinf.Daruma;
import br.com.ctecinf.orm.swing.FormPanelController;
import br.com.ctecinf.model.Parcela;
import br.com.ctecinf.swing.Image;
import br.com.ctecinf.swing.OptionPane;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 *
 * @author Cássio Conceição - ctecinf.com.br
 * @version V2017.3
 * @since 30/03/2017 16:45:42
 * @see http://ctecinf.com.br/code
 *
 */
public class ParcelaForm extends FormPanelController<Parcela> {

    private static final String TITLE = "Cadastro de Parcela";

    public ParcelaForm(Parcela parcela) {
        super(parcela == null ? new Parcela() : parcela);
        init();
    }

    @Override
    protected boolean print() throws Exception {

        Long num = getController().getId();
        String cliente = getController().getCrediario().getCliente().getNome();
        BigDecimal valor = getController().getValorPago();
        String referente = "Pgto. Parcela Num. " + getController().getNumeroParcela();

        if (getController().getId() != null) {

            try {
                Daruma.printRecibo(num.intValue(), cliente, valor.doubleValue(), referente, true);
            } catch (IOException ex) {
                OptionPane.error(ex);
            }

            if (OptionPane.confirm("Deseja imprimir via do estabelecimento?")) {
                try {
                    Daruma.printRecibo(num.intValue(), cliente, valor.doubleValue(), referente, false);
                } catch (IOException ex) {
                    OptionPane.error(ex);
                }
            }
        }

        return true;
    }

    @Override
    protected boolean save(Map params) throws Exception {

        getController().setValues(params);

        if (getController().getCrediario() == null || getController().getCrediario().getId() == null) {
            getFrame().dispose();
            return false;
        }

        boolean ret = super.save(params);

        if (ret) {
            getFrame().dispose();
        }

        return ret;
    }

    @Override
    protected boolean delete() throws Exception {
        if (super.delete()) {
            getFrame().dispose();
            return true;
        } else {
            return false;
        }
    }

    private void init() {

        addRequiredFieldLabel();

        addColumn("numeroParcela", "dataVencimento", "valor", "dataPagamento", "valorPago");

        addAction("Fechar", Image.parse(Image.CLOSE), (e) -> {
            getFrame().dispose();
        });

        setFieldsValues();

        createFrame(TITLE);
    }

}
