/*
 * 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.AdvanceController;
import com.arrebol.apc.model.admin.Advance;
import com.arrebol.apc.model.admin.ExpenseCompany;
import com.arrebol.apc.model.core.HumanResource;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.enums.ActiveStatus;
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("advanceManager")
@ViewScoped
public class AdvanceBean 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 {
                setAdvance(fillDatatableAdvance());
            }
        } catch (Exception e) {
        }
    }

    public List<Advance> fillDatatableAdvance() {

        return getAdvanceCtrl().fillAdvanceDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());
    }

    public List<HumanResource> getHr() {

        return genericCtrl.getAllHRByOffice(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.existStableGeneralBoxByCreatedOn(date)) {
            showMessage(FacesMessage.SEVERITY_WARN, "Día cerrado", "No se pueden agregar más adelantos porque ya se existe un cuadre de caja general de hoy.");
            return;
        }
        
        if(new BigDecimal(amount).compareTo(BigDecimal.ZERO)==0){
            
            showMessage(FacesMessage.SEVERITY_WARN, "Adelanto Incorrecta", "No se pueden dar adelantos de 0");
            return;
        
        }
        
        if(new BigDecimal(amount).compareTo(BigDecimal.ZERO)<0){
            
            showMessage(FacesMessage.SEVERITY_WARN, "Adelanto Incorrecto", "No se puede dar adelanto de un numero negativo");
            return;
        
        }
        
        Advance advanceSave = new Advance();
        advanceSave.setActiveStatus(ActiveStatus.ENEBLED);
        advanceSave.setAmount(new BigDecimal(amount));
        advanceSave.setHumanResource(new HumanResource(humanResourceId));
        advanceSave.setOffice(new Office(getLoggedUser().getOffice().getId()));
        advanceSave.setCreatedOn(date);
        advanceSave.setCreatedBy(getLoggedUser().getId());
        advanceCtrl.saveAdvance(advanceSave);
        advance.clear();
        advance = fillDatatableAdvance();
        humanResourceId = "";
        amount = "";
        FacesMessage msg = new FacesMessage("Nuevo adelanto", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);

    }

    @Override
    public void deleteRow() {
        if (genericCtrl.existStableGeneralBoxByCreatedOn(selectedAdvance.getCreatedOn())) {
            showMessage(FacesMessage.SEVERITY_WARN, "Adelanto", "No se puede borrar porque ya se realizo el cuadre de caja general del día.");
        } else {
            advanceCtrl.updateAdvanceByStatus(ActiveStatus.DISABLED, selectedAdvance.getId(), getLoggedUser().getUser().getId());
            Bitacora bitacora = new Bitacora();
            bitacora.setAction("Eliminar adelanto");
            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 adelanto con monto $"
                    + selectedAdvance.getAmount() + " y fecha " + selectedAdvance.getCreatedOn());

            searchHistoricalAction();
            bitacoraCtrl.saveBitacora(bitacora);
            commentsBitacora = "";
            //advance.remove(selectedAdvance);
            selectedAdvance = null;
            showMessage(FacesMessage.SEVERITY_INFO, "Adelanto Eliminado", "Se eliminó correctamente.");
        }
    }

    public AdvanceController getAdvanceCtrl() {
        return advanceCtrl;
    }

    public void setAdvanceCtrl(AdvanceController advanceCtrl) {
        this.advanceCtrl = advanceCtrl;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

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

    public List<Advance> getAdvance() {
        return advance;
    }

    public void setAdvance(List<Advance> advance) {
        this.advance = advance;
    }

    public List<HumanResource> getHumanResource() {
        return humanResource;
    }

    public void setHumanResource(List<HumanResource> humanResource) {
        this.humanResource = humanResource;
    }

    public String getHumanResourceId() {
        return humanResourceId;
    }

    public void setHumanResourceId(String humanResourceId) {
        this.humanResourceId = humanResourceId;
    }

    public Advance getSelectedAdvance() {
        return selectedAdvance;
    }

    public void setSelectedAdvance(Advance selectedAdvance) {
        this.selectedAdvance = selectedAdvance;
    }

    public String getAmount() {
        return amount;
    }

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

    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 String getCommentsBitacora() {
        return commentsBitacora;
    }

    public void setCommentsBitacora(String commentsBitacora) {
        this.commentsBitacora = commentsBitacora;
    }
    
    private AdvanceController advanceCtrl;
    private GenericController genericCtrl;
    private BitacoraController bitacoraCtrl;
    private GenericValidationController genericValidateController;
    private Date lastStableGeneralBox;
    private String commentsBitacora;

    private List<Advance> advance;
    private List<HumanResource> humanResource;

    private String humanResourceId;
    private Advance selectedAdvance;
    private String amount;

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

        advanceCtrl = new AdvanceController();
        genericCtrl = new GenericController();
        bitacoraCtrl = new BitacoraController();
        setGenericValidateController(new GenericValidationController());
        setLastStableGeneralBox(getGenericValidateController().lastStableGeneralBoxByDate(getLoggedUser().getUser()));
        commentsBitacora = "";
        advance = fillDatatableAdvance();
        humanResource = getHr();
    }

}
