/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.apc.web.beans.admin;

import com.arrebol.apc.controller.BitacoraController;
import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.GenericValidationController;
import com.arrebol.apc.controller.admin.ExpenseCompanyController;
import com.arrebol.apc.controller.admin.StableGeneralBoxController;
import com.arrebol.apc.model.admin.ExpenseCompany;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.enums.ActiveStatus;
import com.arrebol.apc.model.enums.ExpenseCompanyType;
import com.arrebol.apc.model.system.logs.Bitacora;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named("expenseCompanyOutManager")
@ViewScoped
public class ExpenseCompanyOutBean extends GenericBean implements Serializable, Datatable {

    public void searchHistoricalAction() {
        try {
            if (getStarDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setExpenseCompany(fillDatatableExpenseCompany());
            }
        } catch (Exception e) {
        }
    }

    public List<ExpenseCompany> fillDatatableExpenseCompany() {
        return getExpenseCompanyCtrl().fillxpenseCompanyOutDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());
    }

    @Override
    public void editRow(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowCancel(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowReorder(ReorderEvent event) {
        showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1));
    }

    @Override
    public void addRow() {
        Date date = new Date();
        if (genericCtrl.existStableGeneralBoxByCreatedOn(date)) {
            showMessage(FacesMessage.SEVERITY_WARN, "Día cerrado", "No se pueden agregar más gastos administrativos porque ya se existe un cuadre de caja general de hoy.");
            return;
        }
        if(stableGeneralBoxCtrl.getTotalBox().compareTo(new BigDecimal(amount))>=0){
        ExpenseCompany expense = new ExpenseCompany();
        expense.setActiveStatus(ActiveStatus.ENEBLED);
        expense.setExpenseCompanyType(ExpenseCompanyType.PAYMENT_OUT);
        expense.setOffice(new Office(getLoggedUser().getOffice().getId()));
        expense.setAmount(new BigDecimal(amount));
        expense.setDescription(comments);
        expense.setCreatedOn(new Date());
        expense.setCreatedBy(getLoggedUser().getUser().getId());
        expenseCompanyCtrl.saveExpenseCompany(expense);
        expenseCompany.clear();
        
        amount = "";
        comments = "";
        totalCaja= stableGeneralBoxCtrl.getTotalBox();
        FacesMessage msg = new FacesMessage("Nueva Salida", "Se agregó correctamente");
        
        setExpenseCompany(fillDatatableExpenseCompany());
        FacesContext.getCurrentInstance().addMessage(null, msg);}
        else{
            showMessage(FacesMessage.SEVERITY_WARN, "Salida incorrecta", "No se pueden generar la salida  porque es mas grande que la cantidad en caja general.");
        }
    }

    @Override
    public void deleteRow() {
        if (genericCtrl.existStableGeneralBoxByCreatedOn(selectedExpenseCompany.getCreatedOn())) {
            showMessage(FacesMessage.SEVERITY_WARN, "Gasto administrativo", "No se puede borrar porque ya se realizo el cuadre de caja general del día.");
        } else {
            boolean delete = true;
            delete = selectedExpenseCompany.getActiveStatus() == ActiveStatus.ENEBLED ? true : false;

            if (delete) {
                Bitacora bitacora = new Bitacora();
                ExpenseCompany expenseOut = expenseCompanyCtrl.getExpenseById(selectedExpenseCompany.getId());
                bitacora.setAction("Eliminar gasto administrativo");
                bitacora.setCommentsUser(commentsBitacora);
                bitacora.setCreatedBy(getLoggedUser().getUser().getId());
                bitacora.setCreatedOn(new Date());
                bitacora.setNameUser(getLoggedUser().getUser().getUserName());
                bitacora.setOffice(new Office(getLoggedUser().getOffice().getId()));
                bitacora.setDescription("Se eliminó el gasto administrativo con monto $"
                        + expenseOut.getAmount() + " y fecha " + expenseOut.getCreatedOn());

                expenseCompanyCtrl.updateExpenseCompanyByStatus(ActiveStatus.DISABLED, selectedExpenseCompany.getId(), getLoggedUser().getUser().getId());
                // expenseCompany.remove(selectedExpenseCompany);
                searchHistoricalAction();
                bitacoraCtrl.saveBitacora(bitacora);
                commentsBitacora = "";
                selectedExpenseCompany = null;
                showMessage(FacesMessage.SEVERITY_INFO, "Gasto administrativo eliminado", "Se eliminó correctamente.");
            }
        }
    }

    public ExpenseCompanyController getExpenseCompanyCtrl() {
        return expenseCompanyCtrl;
    }

    public void setExpenseCompanyCtrl(ExpenseCompanyController expenseCompanyCtrl) {
        this.expenseCompanyCtrl = expenseCompanyCtrl;
    }

    public List<ExpenseCompany> getExpenseCompany() {
        return expenseCompany;
    }

    public void setExpenseCompany(List<ExpenseCompany> expenseCompany) {
        this.expenseCompany = expenseCompany;
    }

    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public ExpenseCompany getSelectedExpenseCompany() {
        return selectedExpenseCompany;
    }

    public void setSelectedExpenseCompany(ExpenseCompany selectedExpenseCompany) {
        this.selectedExpenseCompany = selectedExpenseCompany;
    }

    public BitacoraController getBitacoraCtrl() {
        return bitacoraCtrl;
    }

    public void setBitacoraCtrl(BitacoraController bitacoraCtrl) {
        this.bitacoraCtrl = bitacoraCtrl;
    }

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

    public void setCommentsBitacora(String commentsBitacora) {
        this.commentsBitacora = commentsBitacora;
    }

    public GenericValidationController getGenericValidateController() {
        return genericValidateController;
    }
    
    public void setGenericValidateController(GenericValidationController genericController) {
        this.genericValidateController = genericController;
    }
    
    public Date getLastStableGeneralBox() {
        return lastStableGeneralBox;
    }

    public BigDecimal getTotalCaja() {
        return totalCaja;
    }

    public void setTotalCaja(BigDecimal totalCaja) {
        this.totalCaja = totalCaja;
    }

    public void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }
    
    private ExpenseCompanyController expenseCompanyCtrl;
    private BitacoraController bitacoraCtrl;
    private GenericController genericCtrl;
    private StableGeneralBoxController stableGeneralBoxCtrl;

    private GenericValidationController genericValidateController;
    private Date lastStableGeneralBox;

    private List<ExpenseCompany> expenseCompany;

    private String amount;
    private String comments;

    private BigDecimal totalCaja;
    private ExpenseCompany selectedExpenseCompany;
    private String commentsBitacora;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        initOneWeekBeforeToCurrdate();

        expenseCompanyCtrl = new ExpenseCompanyController();
        stableGeneralBoxCtrl = new StableGeneralBoxController();
        totalCaja= stableGeneralBoxCtrl.getTotalBox();
        bitacoraCtrl = new BitacoraController();
        genericCtrl = new GenericController();
        setGenericValidateController(new GenericValidationController());
        setLastStableGeneralBox(getGenericValidateController().lastStableGeneralBoxByDate(getLoggedUser().getUser()));
        commentsBitacora = "";
        expenseCompany = fillDatatableExpenseCompany();
    }

}
