/*
 * 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.OtherExpenseController;
import com.arrebol.apc.model.admin.ClosingDay;
import com.arrebol.apc.model.admin.OtherExpense;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.core.User;
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.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("otherExpenseManager")
@ViewScoped
public class OtherExpenseBean 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 {
                setOtherExpense(getOtherExpenseCtrl().fillOtherExpenseDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate(), getUserSelectedId()));
                setTotalValue();
            }
        } catch (Exception e) {
        }
    }

    public List<OtherExpense> fillDatatableOtherExpense() {

        return getOtherExpenseCtrl().fillOtherExpenseDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate(), getUserSelectedId());
    }

    public List<User> getUsers() {

        return genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());
    }

    @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.existStableSmallBoxByCreatedOn(date)) {
            showMessage(FacesMessage.SEVERITY_WARN, "Día cerrado", "No se pueden agregar más gastos porque ya se existe un cuadre de caja chica de hoy.");
            return;
        }
        OtherExpense saveOtherExpense = new OtherExpense();
        saveOtherExpense.setDescription(comments);
        saveOtherExpense.setCreatedBy(getLoggedUser().getUser().getId());
        saveOtherExpense.setCreatedOn(new Date());
        saveOtherExpense.setExpense(new BigDecimal(amount));
        saveOtherExpense.setUser(new User(userId));
        saveOtherExpense.setOffice(new Office(getLoggedUser().getOffice().getId()));
        otherExpenseCtrl.saveOtherExpense(saveOtherExpense);
        otherExpense.clear();
        otherExpense = fillDatatableOtherExpense();
        setTotalValue();
        comments = "";
        userId = "";
        amount = "";
        fecha = new Date();
        FacesMessage msg = new FacesMessage("Nuevo gasto", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    @Override
    public void deleteRow() {
        if (selectedOtherExpense != null) {

            otherExpenseCtrl.deleteOtherExpense(selectedOtherExpense);
            Bitacora bitacora = new Bitacora();
            bitacora.setAction("Eliminar gasto");
            bitacora.setCommentsUser(getCommentsBitacora());
            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ó correctamente el gasto con fecha: " + selectedOtherExpense.getCreatedOn() + ", con monto $"
                    + selectedOtherExpense.getExpense());
            bitacoraCtrl.saveBitacora(bitacora);
            selectedOtherExpense = null;
            otherExpense.clear();
            otherExpense = fillDatatableOtherExpense();
            setTotalValue();
            commentsBitacora = "";

            FacesMessage msg = new FacesMessage("Eliminación de gasto", "Se eliminó correctamente");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        }
    }

    public OtherExpenseController getOtherExpenseCtrl() {
        return otherExpenseCtrl;
    }

    public void setOtherExpenseCtrl(OtherExpenseController otherExpenseCtrl) {
        this.otherExpenseCtrl = otherExpenseCtrl;
    }

    public List<OtherExpense> getOtherExpense() {
        return otherExpense;
    }

    public void setOtherExpense(List<OtherExpense> otherExpense) {
        this.otherExpense = otherExpense;
    }

    public OtherExpense getSelectedOtherExpense() {
        return selectedOtherExpense;
    }

    public void setSelectedOtherExpense(OtherExpense selectedOtherExpense) {
        this.selectedOtherExpense = selectedOtherExpense;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserSelectedId() {
        return userSelectedId;
    }

    public void setUserSelectedId(String userSelectedId) {
        this.userSelectedId = userSelectedId;
    }
    
    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }
    
    public String getComments() {
        return comments;
    }

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

    public String getAmount() {
        return amount;
    }

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

    public Date getFecha() {
        return fecha;
    }

    public void setFecha(Date fecha) {
        this.fecha = fecha;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

    public void setGenericCtrl(GenericController genericCtrl) {
        this.genericCtrl = genericCtrl;
    }

    public GenericValidationController getGenericValidateController() {
        return genericValidateController;
    }

    public void setGenericValidateController(GenericValidationController genericController) {
        this.genericValidateController = genericController;
    }
    
    public Date getLastStableSmallBox() {
        return lastStableSmallBox;
    }

    public void setLastStableSmallBox(Date lastStableSmallBox) {
        this.lastStableSmallBox = lastStableSmallBox;
    }
    
    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 List<ClosingDay> getClosingDayToday() {
        return closingDayToday;
    }

    public void setClosingDayToday(List<ClosingDay> closingDayToday) {
        this.closingDayToday = closingDayToday;
    }
    
    private OtherExpenseController otherExpenseCtrl;
    private GenericController genericCtrl;
    private List<OtherExpense> otherExpense;
    private OtherExpense selectedOtherExpense;
    private List<User> users;
    private String userId;
    private String userSelectedId;
    private BigDecimal total;
    private String comments;
    private String amount;
    private Date fecha;
    
    private BitacoraController bitacoraCtrl;
    private String commentsBitacora;
    private GenericValidationController genericValidateController;
    private Date lastStableSmallBox;
    private List<ClosingDay> closingDayToday;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        
        otherExpenseCtrl = new OtherExpenseController();
        genericCtrl = new GenericController();
        bitacoraCtrl = new BitacoraController();
        setGenericValidateController(new GenericValidationController());
        setLastStableSmallBox(getGenericValidateController().lastStableSmallBoxByDate(getLoggedUser().getUser()));
        setClosingDayToday(getGenericValidateController().allClosingDayByDate());
        
        initOneWeekBeforeToCurrdate();

        otherExpense = fillDatatableOtherExpense();
        setTotalValue();
        users = getUsers();
    }

    private void setTotalValue() {
        if (otherExpense != null && !otherExpense.isEmpty()) {
            setTotal(otherExpense.stream().map(OtherExpense::getExpense).reduce(BigDecimal::add).get());
        } else {
            setTotal(BigDecimal.ZERO);
        }
    }
}
