/*
 * 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.MoneyDailyController;
import com.arrebol.apc.controller.admin.StableGeneralBoxController;
import com.arrebol.apc.model.admin.MoneyDaily;
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.model.views.MoneyDailyByUserCertifier;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
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("moneyDailyManager")
@ViewScoped
public class MoneyDailyBean 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 {
                setMoneyDaily(getMoneyDailyCtrl().fillMoneyDailyDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate(), getUserSelectedId()));
                setTotalValue();
            }
        } catch (Exception e) {
        }
    }

    public List<MoneyDaily> fillDatatableMoneyDaily() {

        return getMoneyDailyCtrl().fillMoneyDailyDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate(), getUserSelectedId());
    }

    public List<User> getUsers() {

        return genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());
    }
    
    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;
    }

    @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() {
        /*if(!genericCtrl.verifyStableGeneralBoxVsClosingDay(getLoggedUser().getOffice().getId()))
        {
            FacesMessage msg = new FacesMessage("Día laborable no cuadrado.", "Falta de realizar un cuadre de caja general en el último día laborable.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return;
        }*/
        Date date = new Date();
        if (genericCtrl.existStableGeneralBoxByCreatedOn(date)) {
            showMessage(FacesMessage.SEVERITY_WARN, "Día cerrado", "No se pueden agregar más inicios porque ya se existe un cuadre de caja general de hoy.");
            return;
        }
        
        if(stableGeneralBoxCtrl.getTotalBox().compareTo(new BigDecimal(amount))>=0){
        MoneyDaily money = new MoneyDaily();
        money.setMoneyDailyDate(new Date());
        money.setOffice(new Office(getLoggedUser().getOffice().getId()));
        money.setAmount(new BigDecimal(amount));
        money.setUser(new User(userId));
        money.setCreatedOn(new Date());
        money.setCreatedBy(getLoggedUser().getId());
        moneyDailyCtrl.saveMoneyDaily(money);
        moneyDaily.clear();
        moneyDaily = fillDatatableMoneyDaily();
        setTotalValue();
        totalCaja= stableGeneralBoxCtrl.getTotalBox();
        amount = "";
        userId = "";
        FacesMessage msg = new FacesMessage("Nueva entrega de dinero", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        }else{
        showMessage(FacesMessage.SEVERITY_WARN, "Incicio incorrecto", "No se pueden agregar el inicio porque es mas grande que la cantidad en caja general.");
        }
        
    }

    @Override
    public void deleteRow() {
        
            if (genericCtrl.existStableSmallBoxByCreatedOn(selectedMoneyDaily.getCreatedOn())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Inicio", "No se puede borrar porque ya se realizo el cuadre de caja chica del día.");
            } else {
                Bitacora bitacora = new Bitacora();
                MoneyDaily money = moneyDailyCtrl.getMoneyDailyById(selectedMoneyDaily.getId());
                bitacora.setAction("Eliminar inicio");
                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 inicio del asesor " + money.getUser().getUserName() + " con monto $"
                        + money.getAmount() + " y fecha " + money.getCreatedOn());
                moneyDailyCtrl.deleteMoneyDaily(selectedMoneyDaily);
                bitacoraCtrl.saveBitacora(bitacora);
                commentsBitacora = "";
                selectedMoneyDaily = null;
                moneyDaily.clear();
                moneyDaily = fillDatatableMoneyDaily();
                setTotalValue();
                FacesMessage msg = new FacesMessage("Eliminación de inicio", "Se eliminó correctamente");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        
    }

    public MoneyDailyController getMoneyDailyCtrl() {
        return moneyDailyCtrl;
    }

    public void setMoneyDailyCtrl(MoneyDailyController moneyDailyCtrl) {
        this.moneyDailyCtrl = moneyDailyCtrl;
    }

    public List<MoneyDaily> getMoneyDaily() {
        return moneyDaily;
    }

    public void setMoneyDaily(List<MoneyDaily> moneyDaily) {
        this.moneyDaily = moneyDaily;
    }

    public String getUserId() {
        return userId;
    }

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

    public String getAmount() {
        return amount;
    }

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

    public MoneyDaily getSelectedMoneyDaily() {
        return selectedMoneyDaily;
    }

    public void setSelectedMoneyDaily(MoneyDaily selectedMoneyDaily) {
        this.selectedMoneyDaily = selectedMoneyDaily;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

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

    public List<MoneyDailyByUserCertifier> getMoneyDailyCertifier() {
        return moneyDailyCertifier;
    }

    public void setMoneyDailyCertifier(List<MoneyDailyByUserCertifier> moneyDailyCertifier) {
        this.moneyDailyCertifier = moneyDailyCertifier;
    }

    public MoneyDaily getSelectedMoneyDailyCertifier() {
        return selectedMoneyDailyCertifier;
    }

    public void setSelectedMoneyDailyCertifier(MoneyDaily selectedMoneyDailyCertifier) {
        this.selectedMoneyDailyCertifier = selectedMoneyDailyCertifier;
    }

    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 void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }

    public StableGeneralBoxController getStableGeneralBoxCtrl() {
        return stableGeneralBoxCtrl;
    }

    public void setStableGeneralBoxCtrl(StableGeneralBoxController stableGeneralBoxCtrl) {
        this.stableGeneralBoxCtrl = stableGeneralBoxCtrl;
    }

    public BigDecimal getTotalCaja() {
        return totalCaja;
    }

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

    private MoneyDailyController moneyDailyCtrl;
    private GenericController genericCtrl;
    private BitacoraController bitacoraCtrl;
    private GenericValidationController genericValidateController;
    private StableGeneralBoxController stableGeneralBoxCtrl;
    private Date lastStableGeneralBox;

    private List<MoneyDaily> moneyDaily;
    private List<MoneyDailyByUserCertifier> moneyDailyCertifier;
    private List<User> users;
    private String userSelectedId;
    private BigDecimal total;
    private BigDecimal totalCaja;

    private String userId;
    private String amount;
    private String commentsBitacora;

    private MoneyDaily selectedMoneyDaily;
    private MoneyDaily selectedMoneyDailyCertifier;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        
        stableGeneralBoxCtrl = new StableGeneralBoxController();

        moneyDailyCtrl = new MoneyDailyController();
        genericCtrl = new GenericController();
        bitacoraCtrl = new BitacoraController();
        setGenericValidateController(new GenericValidationController());
        setLastStableGeneralBox(getGenericValidateController().lastStableGeneralBoxByDate(getLoggedUser().getUser()));

        initOneWeekBeforeToCurrdate();
        
        totalCaja= stableGeneralBoxCtrl.getTotalBox();
        moneyDaily = fillDatatableMoneyDaily();
        setTotalValue();
        moneyDailyCertifier = moneyDailyCtrl.findAllAmountByUserCertifierView(getLoggedUser().getOffice().getId());
        users = getUsers();
        commentsBitacora = "";

    }

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