/*
 * 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.taxiservicios.beans.admin;

import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.BitacoraController;
import com.arrebol.taxiservicios.controller.admin.ExpenseCompanyController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.catalog.BankCardController;
import com.arrebol.taxiservicios.controller.catalog.BankCardKardexController;
import com.arrebol.taxiservicios.controller.catalog.ExpenseIncomeCatalogController;
import com.arrebol.taxiservicios.model.admin.ExpenseCompany;
import com.arrebol.taxiservicios.model.catalog.BankCard;
import com.arrebol.taxiservicios.model.catalog.BankCardKardex;
import com.arrebol.taxiservicios.model.catalog.ExpenseIncomeCatalog;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BankCardKardexType;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseCompanyType;
import com.arrebol.taxiservicios.model.enums.ExpenseIncomeType;
import com.arrebol.taxiservicios.model.enums.ExpenseStatusType;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named("expenseCompanyPaymentOutBean")
@ViewScoped
public class ExpenseCompanyPaymentOutBean extends TaxiGenericBean implements Serializable, Datatable {

    /**
     * Update expense company list between start date and end date.
     */
    public void updateExpenseCompanyList() {
        logger.info("updateExpenseCompanyList");
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("payment.out"),
                        getBundlePropertyFile().getString("start.date.after.error"));
            } else {
                setUpDates(false);
                setExpenseCompanies(
                        getController().findExpenseCompanyByTypeAndBetweenDates(
                                ExpenseCompanyType.PAYMENT_OUT,
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId())
                );
            }
        } catch (Exception e) {
            logger.error("updateExpenseCompanyList", e);
        }
    }
public void autorizarPending() {
        logger.info("noPrintSale");

        try {
            boolean success = getController().autorizarExpense(getExpenseCompanyToUpdate().getId(), getLoggedUser());

            if (success) {

                BankCardKardex bankCardKardexObj = new BankCardKardex();

                bankCardKardexObj.setBankCard(getExpenseCompanyToUpdate().getBankCard());
                bankCardKardexObj.setAmount(getExpenseCompanyToUpdate().getAmount().doubleValue());
                bankCardKardexObj.setAmountBefore(getExpenseCompanyToUpdate().getBankCard().getBalance());

                if (getExpenseCompanyToUpdate().getIdExpenseType().getExpenseIncomeCatalogType().equals(ExpenseIncomeType.EARNING)) {

                    bankCardKardexObj.setAmountAfter(bankCardKardexObj.getAmountBefore() + bankCardKardexObj.getAmount());
                    bankCardKardexObj.setKardexType(BankCardKardexType.INCOME);
                    bankCardKardexObj.setDescription("Pago por gasto administrativo del tipo " + getExpenseCompanyToUpdate().getIdExpenseType().getName());
               
                } else if (getExpenseCompanyToUpdate().getIdExpenseType().getExpenseIncomeCatalogType().equals(ExpenseIncomeType.EXPENSE)) {
                
                    bankCardKardexObj.setAmountAfter(bankCardKardexObj.getAmountBefore() - bankCardKardexObj.getAmount());
                    bankCardKardexObj.setKardexType(BankCardKardexType.EXPENSE);
                    bankCardKardexObj.setDescription("Cobro por gasto adminstrativo del tipo " + getExpenseCompanyToUpdate().getIdExpenseType().getName());
                
                }

                bankCardKardexObj.setLocation(getExpenseCompanyToUpdate().getLocation());

                BankCardKardexController bankCardKardexCtrl = new BankCardKardexController();
                bankCardKardexCtrl.save(bankCardKardexObj, getLoggedUser().getId());

                BankCard bankCard = getExpenseCompanyToUpdate().getBankCard();

                bankCard.setBalance(bankCardKardexObj.getAmountAfter());

                BankCardController bankCardCtrl = new BankCardController();

                bankCardCtrl.save(bankCard, getLoggedUser().getId());

                setExpenseCompanyToUpdate(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Autorizar",
                        "Se autorizó correctamente");
                setExpenseCompanyPending(getController().fillExpenseDataTablePendingDeposit(ExpenseCompanyType.PAYMENT_IN,getLoggedUser().getLocation()));
            } else {
                logger.error("Sale " + getExpenseCompanyToUpdate() + "was not changed to no print");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Autorizar",
                        "No se pudo autorizar");
            }

        } catch (Exception e) {
            logger.error("autorizar: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("sale.noprint.title"),
                    getBundlePropertyFile().getString("sale.noprint.exception.desc"));
        }

    }
    @Override
    public void addRow() {
        logger.info("addRow");

        if (getGenericController().existStableGeneralBoxByCurdate(getLoggedUser())) {
            showMessage(FacesMessage.SEVERITY_WARN,
                    "Dia cerrado",
                    "No se pueden generar más gastos administrativos porque ya existe un cuadre de caja general del día");
            return;
        }
        try {
            ExpenseCompany ec = new ExpenseCompany(
                    UUID.randomUUID().toString(),
                    getAmount(),
                    getReason(),
                    ExpenseCompanyType.PAYMENT_OUT,
                    BasicType.ENEBLED,
                    new User(getLoggedUser().getId(), ""),
                    new Date(),
                    getLoggedUser().getLocation());

            ec.setIdExpenseType(new ExpenseIncomeCatalog(getExpenseIncomeId()));
            
            if (isDeposit()) {
                ec.setBankCard(new BankCard(getBankCardId()));
                ec.setDepositStatus(ExpenseStatusType.PENDING);
            } else {
                ec.setDepositStatus(ExpenseStatusType.AUTHORIZED);
            }
            
            if (getController().saveExpenseCompany(ec)) {
                setUpDates(false);
                setExpenseCompanies(
                        getController().findExpenseCompanyByTypeAndBetweenDates(
                                ExpenseCompanyType.PAYMENT_OUT,
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId())
                );

                setAmount(null);
                setReason(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("payment.out"),
                        getBundlePropertyFile().getString("payment.out.add.success.desc"));
            } else {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("payment.out"),
                        getBundlePropertyFile().getString("payment.out.add.exception.desc"));
            }
        } catch (Exception e) {
            logger.error("addRow", e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("payment.out"),
                    getBundlePropertyFile().getString("payment.out.add.exception.desc"));
        }
    }

    @Override
    public void deleteRow() {
        logger.info("deleteRow");
        try {

            if (getGenericController().existStableGeneralBoxByCurdate(getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Dia cerrado",
                        "No se pueden eliminar mas gastos administrativos porque ya existe un cuadre de caja general del día");
                return;
            }
            if (getController().updateExpenseCompanyStatus(getExpenseCompanyToUpdate().getId(), BasicType.DISABLED, new User(getLoggedUser().getId(), ""))) {

                if (null == getCommentsBitacora() || getCommentsBitacora().trim().equals("")) {
                    setCommentsBitacora("El usuario " + getLoggedUser().getUserName() + " no agrego comentarios a la hora de borrar este gasto administrativo");
                }

                String actionBitacora = "Eliminar gasto administrativo";
                String descBitacora = "Se eliminó el gasto adminitrativo con monto "
                        + currencyFormatNumber(getExpenseCompanyToUpdate().getAmount()) + " y fecha " + getExpenseCompanyToUpdate().getCreatedOn();

                getBitacoraController().saveNewRecordInBitacora(createNewRecordInBitacora(UUID.randomUUID().toString(), actionBitacora, getCommentsBitacora(), descBitacora),
                        getLoggedUser().getLocation().getId());
                getExpenseCompanies().remove(getExpenseCompanyToUpdate());

                setExpenseCompanyToUpdate(null);
                setCommentsBitacora("");
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("payment.out"),
                        getBundlePropertyFile().getString("payment.out.delete.success.desc"));
            } else {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("payment.out"),
                        getBundlePropertyFile().getString("payment.out.delete.exception.desc"));
            }
        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("payment.out"),
                    getBundlePropertyFile().getString("payment.out.delete.exception.desc"));
        }
    }

    @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) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * Setup start date and end date.
     *
     * @param init True if comes from @PostConstruct otherwise false.
     */
    private void setUpDates(boolean init) {
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();

        if (!init) {
            startCalendar.setTime(getStartDate());
            endCalendar.setTime(getEndDate());
        } else {
            startCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            endCalendar.setTime(new Date());
        }

        startCalendar.add(Calendar.HOUR_OF_DAY, 0);
        startCalendar.add(Calendar.MINUTE, 0);
        startCalendar.add(Calendar.SECOND, 0);
        startCalendar.add(Calendar.MILLISECOND, 0);

        endCalendar.add(Calendar.HOUR_OF_DAY, 22);
        endCalendar.add(Calendar.MINUTE, 59);
        endCalendar.add(Calendar.SECOND, 59);
        endCalendar.add(Calendar.MILLISECOND, 0);

        setStartDate(startCalendar.getTime());
        setEndDate(endCalendar.getTime());
    }

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();

            setUpDates(true);
            setController(new ExpenseCompanyController());
            setBitacoraController(new BitacoraController());
            setGenericController(new GenericValidationController());
            setExpenseIncomeCatalogController(new ExpenseIncomeCatalogController());
            setExpenseIncomeCatalog(getExpenseIncomeCatalogController().findExpenseCatalogGeneralBox());
            setLastStableGeneralBox(getGenericController().lastStableGeneralBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()));
            setBankCardController(new BankCardController());
            setExpenseCompanies(
                    getController().findExpenseCompanyByTypeAndBetweenDates(
                            ExpenseCompanyType.PAYMENT_OUT,
                            getStartDate(),
                            getEndDate(),
                            getLoggedUser().getLocation().getId())
            );

            setExpenseCompanyPending(getController().fillExpenseDataTablePendingDeposit(ExpenseCompanyType.PAYMENT_OUT, getLoggedUser().getLocation()));
            setBankCards(getBankCardController().findAllBankCardsByLocation(getLoggedUser().getLocation().getId()));
            setDeposit(false);
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private ExpenseCompanyController controller;
    private GenericValidationController genericController;
    private ExpenseIncomeCatalogController expenseIncomeCatalogController;
    private Date lastStableGeneralBox;
    private boolean hayCuadre;
    private List<ExpenseCompany> expenseCompanies;
    private ExpenseCompany expenseCompanyToUpdate;
    private ExpenseCompany newExpenseCompany;
    private Date startDate;
    private Date endDate;
    private BigDecimal amount;
    private String reason;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private boolean deposit;
    private String bankCardId;
    private BankCardController bankCardController;
    private List<BankCard> bankCards;
    private List<ExpenseCompany> expenseCompanyPending;

    private List<ExpenseIncomeCatalog> expenseIncomeCatalog;
    private String expenseIncomeId;

    public boolean isHayCuadre() {
        return hayCuadre;
    }

    public void setHayCuadre(boolean hayCuadre) {
        this.hayCuadre = hayCuadre;
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

    public void setGenericController(GenericValidationController genericController) {
        this.genericController = genericController;
    }

    public Date getLastStableGeneralBox() {
        return lastStableGeneralBox;
    }

    public void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }

    public ExpenseCompanyController getController() {
        return controller;
    }

    public void setController(ExpenseCompanyController controller) {
        this.controller = controller;
    }

    public List<ExpenseCompany> getExpenseCompanies() {
        return expenseCompanies;
    }

    public void setExpenseCompanies(List<ExpenseCompany> expenseCompanies) {
        this.expenseCompanies = expenseCompanies;
    }

    public ExpenseCompany getExpenseCompanyToUpdate() {
        return expenseCompanyToUpdate;
    }

    public void setExpenseCompanyToUpdate(ExpenseCompany expenseCompanyToUpdate) {
        this.expenseCompanyToUpdate = expenseCompanyToUpdate;
    }

    public ExpenseCompany getNewExpenseCompany() {
        return newExpenseCompany;
    }

    public void setNewExpenseCompany(ExpenseCompany newExpenseCompany) {
        this.newExpenseCompany = newExpenseCompany;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public BigDecimal getAmount() {
        return amount;
    }

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

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public BitacoraController getBitacoraController() {
        return bitacoraController;
    }

    public void setBitacoraController(BitacoraController bitacoraController) {
        this.bitacoraController = bitacoraController;
    }

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

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

    public List<ExpenseIncomeCatalog> getExpenseIncomeCatalog() {
        return expenseIncomeCatalog;
    }

    public void setExpenseIncomeCatalog(List<ExpenseIncomeCatalog> expenseIncomeCatalog) {
        this.expenseIncomeCatalog = expenseIncomeCatalog;
    }

    public String getExpenseIncomeId() {
        return expenseIncomeId;
    }

    public void setExpenseIncomeId(String expenseIncomeId) {
        this.expenseIncomeId = expenseIncomeId;
    }

    public ExpenseIncomeCatalogController getExpenseIncomeCatalogController() {
        return expenseIncomeCatalogController;
    }

    public void setExpenseIncomeCatalogController(ExpenseIncomeCatalogController expenseIncomeCatalogController) {
        this.expenseIncomeCatalogController = expenseIncomeCatalogController;
    }

    public boolean isDeposit() {
        return deposit;
    }

    public void setDeposit(boolean deposit) {
        this.deposit = deposit;
    }

    public String getBankCardId() {
        return bankCardId;
    }

    public void setBankCardId(String bankCardId) {
        this.bankCardId = bankCardId;
    }

    public BankCardController getBankCardController() {
        return bankCardController;
    }

    public void setBankCardController(BankCardController bankCardController) {
        this.bankCardController = bankCardController;
    }

    public List<BankCard> getBankCards() {
        return bankCards;
    }

    public void setBankCards(List<BankCard> bankCards) {
        this.bankCards = bankCards;
    }

    public List<ExpenseCompany> getExpenseCompanyPending() {
        return expenseCompanyPending;
    }

    public void setExpenseCompanyPending(List<ExpenseCompany> expenseCompanyPending) {
        this.expenseCompanyPending = expenseCompanyPending;
    }

    private static final long serialVersionUID = -136031528440947006L;
    final Logger logger = LogManager.getLogger(ExpenseCompanyPaymentOutBean.class);
}
