/*
 * 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.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.model.views.EnabledUserDetailsView;
import com.arrebol.apc.model.views.TransferView;
import com.arrebol.apc.service.BitacoraService;
import com.arrebol.apc.service.GenericValidationService;
import com.arrebol.apc.service.admin.TransferService;
import com.arrebol.apc.service.views.EnabledUserDetailsViewService;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named(value = "transferUpgradeBean")
@ViewScoped
public class TransferUpgradeBean extends GenericBean implements Serializable {

    /**
     *
     */
    public void addRow() {
        Date date = new Date();
        if (genericValidationService.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;
        }

        try {
            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());
            transferService.saveTransfer(saveTransfer);

            setAmountToTransfer("");
            setUserReceiveId("");
            setUserSendId("");

            showMessage(FacesMessage.SEVERITY_INFO, "Transferencia", "No se agrego correctamente la transferencia");
        } catch (Exception e) {
            logger.error("addRow", e);
            showMessage(FacesMessage.SEVERITY_ERROR, "Transferencia", "No se agrego correctamente la transferencia");
        }

    }

    /**
     *
     */
    public void deleteRow() {
        try {
            transferService.updateTransferByStatus(ActiveStatus.DISABLED, getSelectedTransfer().getId(), getLoggedUser().getUser().getId());

            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: " + getSelectedTransfer().getStrCreatedOn() + ", con monto $"
                    + selectedTransfer.getAmountToTransfer());
            bitacoraService.saveBitacora(bitacora);
            setSelectedTransfer(null);
            setCommentsBitacora("");
            showMessage(FacesMessage.SEVERITY_INFO, "Transferencia", "Se eliminó correctamente la transferencia");
        } catch (Exception e) {
            logger.error("deleteRow", e);
            showMessage(FacesMessage.SEVERITY_ERROR, "Transferencia", "No se eliminó correctamente la transferencia");
        }

    }

    /**
     *
     */
    private void loadingLazyDataTable() {
        try {
            setTransfers(new LazyDataModel<TransferView>() {
                private List<TransferView> lazyEntityList;

                @Override
                public List<TransferView> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filterBy) {
                    try {
                        Long total = transferService.countPaginator(filterBy, getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());

                        setRowCount(total.intValue());

                        lazyEntityList = transferService.lazyEntityListPaginator(first, pageSize, sortField, sortOrder, filterBy, getLoggedUser().getOffice().getId(), getStarDate(), getEndDate());

                        return lazyEntityList;
                    } catch (Exception e) {
                        logger.error("lazy Entity List", e);
                        setRowCount(0);
                        return new ArrayList<>();
                    }
                }

                @Override
                public String getRowKey(TransferView row) {
                    return row.getId();
                }

                @Override
                public TransferView getRowData(String rowKey) {
                    return lazyEntityList
                            .stream()
                            .filter(row -> rowKey.equals(row.getId()))
                            .findFirst()
                            .orElse(null);
                }
            }
            );
        } catch (Exception e) {
            logger.error("Lazy Data Model Customer View ", e);
        }
    }

    /**
     *
     */
    private void fillUsersComboBoxes() {
        setUserSend(enabledUserDetailsViewService.findEnabledUsersByOffice(getLoggedUser().getOffice().getId()));
        setUserReceive(getUserSend());
    }

    @PostConstruct
    public void init() {
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setLastStableSmallBox(genericValidationService.lastStableSmallBoxByDate(getLoggedUser().getUser()));
            loadingLazyDataTable();
            fillUsersComboBoxes();
        } catch (Exception e) {
            logger.error("TransferUpgradeBean init", e);
        }
    }

    final Logger logger = LogManager.getLogger(getClass());

    @Inject
    private TransferService transferService;
    @Inject
    private GenericValidationService genericValidationService;
    @Inject
    private BitacoraService bitacoraService;
    @Inject
    private EnabledUserDetailsViewService enabledUserDetailsViewService;

    private Date lastStableSmallBox;
    private LazyDataModel<TransferView> transfers;
    private TransferView selectedTransfer;
    private String commentsBitacora;
    private List<EnabledUserDetailsView> userSend;
    private List<EnabledUserDetailsView> userReceive;
    private String userSendId;
    private String userReceiveId;
    private String amountToTransfer;

    public Date getLastStableSmallBox() {
        return lastStableSmallBox;
    }

    public void setLastStableSmallBox(Date lastStableSmallBox) {
        this.lastStableSmallBox = lastStableSmallBox;
    }

    public LazyDataModel<TransferView> getTransfers() {
        return transfers;
    }

    public void setTransfers(LazyDataModel<TransferView> transfers) {
        this.transfers = transfers;
    }

    public TransferView getSelectedTransfer() {
        return selectedTransfer;
    }

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

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

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

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

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

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

    public void setUserReceive(List<EnabledUserDetailsView> 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;
    }

}
