/*
 * 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.TransferController;
import com.arrebol.apc.model.admin.Transfer;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.core.User;
import com.arrebol.apc.model.enums.ActionStatus;
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("transferManager")
@ViewScoped
public class TransferBean 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 {
                setTransfer(getTransferCtrl().fillTransferDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate()));
            }
        } catch (Exception e) {
        }
    }

    public List<Transfer> fillDatatableTransfer() {

        return getTransferCtrl().fillTransferDatatable(getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());
    }

    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 transferencias porque ya se existe un cuadre de caja chica de hoy.");
            return;
        }
        
        Transfer saveTransfer = new Transfer();
        saveTransfer.setActionStatus(ActionStatus.PENDING);
        saveTransfer.setActiveStatus(ActiveStatus.ENEBLED);
        saveTransfer.setOffice(new Office(getLoggedUser().getOffice().getId()));
        saveTransfer.setUserReceiver(new User(userReceiveId));
        saveTransfer.setUserTransmitter(new User(userSendId));
        saveTransfer.setAmountToTransfer(new BigDecimal(amountToTransfer));
        saveTransfer.setCreatedBy(getLoggedUser().getId());
        saveTransfer.setCreatedOn(new Date());
        transferCtrl.saveTransfer(saveTransfer);
        transfer.clear();
        transfer = fillDatatableTransfer();
        amountToTransfer = "";
        userReceiveId = "";
        userSendId = "";
        FacesMessage msg = new FacesMessage("Nueva transferencia", "Se agregó correctamente");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    @Override
    public void deleteRow() {
        transferCtrl.updateTransferByStatus(ActiveStatus.DISABLED, selectedTransfer.getId(), getLoggedUser().getUser().getId());
        searchHistoricalAction();
        Bitacora bitacora = new Bitacora();
        bitacora.setAction("Eliminar transferencia");
        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 la transferencia con fecha: " + selectedTransfer.getCreatedOn() + ", con monto $"
                + selectedTransfer.getAmountToTransfer());
        bitacoraCtrl.saveBitacora(bitacora);
        selectedTransfer = null;
        commentsBitacora = "";
        showMessage(FacesMessage.SEVERITY_INFO, "Transferencia Eliminada", "Se eliminó correctamente.");
    }

    public TransferController getTransferCtrl() {
        return transferCtrl;
    }

    public void setTransferCtrl(TransferController transferCtrl) {
        this.transferCtrl = transferCtrl;
    }

    public List<Transfer> getTransfer() {
        return transfer;
    }

    public void setTransfer(List<Transfer> transfer) {
        this.transfer = transfer;
    }

    public Transfer getSelectedTransfer() {
        return selectedTransfer;
    }

    public void setSelectedTransfer(Transfer selectedTransfer) {
        this.selectedTransfer = selectedTransfer;
    }

    public List<User> getUserSend() {
        return userSend;
    }

    public void setUserSend(List<User> userSend) {
        this.userSend = userSend;
    }

    public List<User> getUserReceive() {
        return userReceive;
    }

    public void setUserReceive(List<User> userReceive) {
        this.userReceive = userReceive;
    }

    public String getUserSendId() {
        return userSendId;
    }

    public void setUserSendId(String userSendId) {
        this.userSendId = userSendId;
    }

    public String getUserReceiveId() {
        return userReceiveId;
    }

    public void setUserReceiveId(String userReceiveId) {
        this.userReceiveId = userReceiveId;
    }

    public String getAmountToTransfer() {
        return amountToTransfer;
    }

    public void setAmountToTransfer(String amountToTransfer) {
        this.amountToTransfer = amountToTransfer;
    }

    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;
    }
    
    private TransferController transferCtrl;
    private GenericController genericCtrl;
    private BitacoraController bitacoraCtrl;
    private String commentsBitacora;
    private GenericValidationController genericValidateController;
    private Date lastStableSmallBox;

    private List<Transfer> transfer;
    private List<User> userSend;
    private List<User> userReceive;

    private String userSendId;
    private String userReceiveId;
    private String amountToTransfer;

    private Transfer selectedTransfer;

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

        transferCtrl = new TransferController();
        genericCtrl = new GenericController();
        bitacoraCtrl = new BitacoraController();
        setGenericValidateController(new GenericValidationController());
        setLastStableSmallBox(getGenericValidateController().lastStableSmallBoxByDate(getLoggedUser().getUser()));
        
        initOneWeekBeforeToCurrdate();

        transfer = fillDatatableTransfer();
        userSend = getUsers();
        userReceive = getUsers();
    }

}
