/*
 * 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.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.TaxesController;
import com.arrebol.taxiservicios.controller.catalog.BankCardController;
import com.arrebol.taxiservicios.controller.catalog.BankCardKardexController;
import com.arrebol.taxiservicios.model.admin.Taxes;
import com.arrebol.taxiservicios.model.catalog.BankCard;
import com.arrebol.taxiservicios.model.catalog.BankCardKardex;
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.ExpenseStatusType;
import com.arrebol.taxiservicios.model.enums.TaxesType;
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 Oscar Vargas
 */
@Named("taxesBean")
@ViewScoped
public class TaxesBean extends TaxiGenericBean implements Serializable, Datatable {

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

    @Override
    public void addRow() {
        logger.info("addRow");
        
        if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden generar más impuestos porque ya existe un cuadre de caja general del día");
                return;
            }
        try {
            
            TaxesType tmp = null;
            if (getTipo().equals("IVA")) {
                tmp = TaxesType.IVA;
            }
            if (getTipo().equals("ISR")) {
                tmp = TaxesType.ISR;
            }
            if (getTipo().equals("IMSS")) {
                tmp = TaxesType.IMSS;
            }
            if (getTipo().equals("IMPUESTO_CEDULAR")) {
                tmp = TaxesType.IMPUESTO_CEDULAR;
            }
            if (getTipo().equals("NOMINA")) {
                tmp = TaxesType.NOMINA;
            }
            if (getTipo().equals("OTROS")) {
                tmp = TaxesType.OTROS;
            }
            
            Taxes ec = new Taxes(
                    UUID.randomUUID().toString(),
                    getAmount(),
                    getReason(),
                    tmp,
                    BasicType.ENEBLED,
                    new User(getLoggedUser().getId(), ""),
                    new Date(),
                    getLoggedUser().getLocation());
            
            if(isDeposit()){
                ec.setBankCard(new BankCard(getBankCardId()));
                ec.setDepositStatus(ExpenseStatusType.PENDING);
            }else{
                ec.setDepositStatus(ExpenseStatusType.AUTHORIZED);
            }

            if (getController().saveTaxes(ec)) {
                setUpDates(false);
                setTaxes(
                        getController().findTaxesBetweenDates(
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId())
                );

                setAmount(null);
                setReason(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Impuestos",
                        "Se agregó correctamente");
            } else {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Impuestos",
                        "No se pudo agregar el impuesto");
            }
        } catch (Exception e) {
            logger.error("addRow", e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    "Impuestos",
                    "Ocurrio un error");
        }
    }
    
    public void autorizarPending() {
        logger.info("noPrintSale");

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

            if (success) {

                BankCardKardex bankCardKardexObj = new BankCardKardex();

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

                
                    bankCardKardexObj.setAmountAfter(bankCardKardexObj.getAmountBefore() - bankCardKardexObj.getAmount());
                    bankCardKardexObj.setKardexType(BankCardKardexType.EXPENSE);
                    bankCardKardexObj.setDescription("Cobro por impuesto del tipo " + getTaxesToUpdate().getDescription());
                
                

                bankCardKardexObj.setLocation(getTaxesToUpdate().getLocation());

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

                BankCard bankCard = getTaxesToUpdate().getBankCard();

                bankCard.setBalance(bankCardKardexObj.getAmountAfter());

                BankCardController bankCardCtrl = new BankCardController();

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

                setTaxesToUpdate(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Autorizar",
                        "Se autorizó correctamente");
               setTaxesPending(getController().findTaxesPending(
                          getLoggedUser().getLocation().getId()));
            } else {
                logger.error("Sale " + getTaxesToUpdate() + "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 deleteRow() {
        logger.info("deleteRow");
        try {

            if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden eliminar mas impuestos porque ya existe un cuadre de caja general del día");
                return;
            }
            if (getController().updateTaxesStatus(getTaxesToUpdate().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 impuesto");
                }

                String actionBitacora = "Eliminar impuesto";
                String descBitacora = "Se eliminó el impuesto con monto "
                        + currencyFormatNumber(getTaxesToUpdate().getAmount()) + " y fecha " + getTaxesToUpdate().getCreatedOn();

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

                setTaxesToUpdate(null);
                setCommentsBitacora("");
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Impuestos",
                        "Se eliminó correctamente");
            } else {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Impuestos",
                        "No se pudo eliminar");
            }
        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                     "Impuestos",
                    "Ocurrió un error");
        }
    }

    @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 TaxesController());
            setBitacoraController(new BitacoraController());
            setGenericController(new GenericValidationController());
            setLastStableGeneralBox(getGenericController().lastStableGeneralBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()));
            setBankCardController(new BankCardController());
            setTaxes(
                    getController().findTaxesBetweenDates(
                            getStartDate(),
                            getEndDate(),
                            getLoggedUser().getLocation().getId())
            );
            setTaxesPending(getController().findTaxesPending(
                          getLoggedUser().getLocation().getId()));
             setBankCards(getBankCardController().findAllBankCardsByLocation(getLoggedUser().getLocation().getId()));
            setDeposit(false);
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private TaxesController controller;
    private GenericValidationController genericController;
    private Date lastStableGeneralBox;
    private boolean hayCuadre;
    private List<Taxes> taxes;
    private Taxes taxesToUpdate;
    private Taxes taxesCompany;
    private Date startDate;
    private Date endDate;
    private BigDecimal amount;
    private String reason;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private String tipo;
    
    private boolean deposit;
    private String bankCardId;
    private BankCardController bankCardController;
    private List<BankCard> bankCards;
    private List<Taxes> taxesPending;

    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 TaxesController getController() {
        return controller;
    }

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

    public List<Taxes> getTaxes() {
        return taxes;
    }

    public void setTaxes(List<Taxes> taxes) {
        this.taxes = taxes;
    }

    public Taxes getTaxesToUpdate() {
        return taxesToUpdate;
    }

    public void setTaxesToUpdate(Taxes taxesToUpdate) {
        this.taxesToUpdate = taxesToUpdate;
    }

    public Taxes getTaxesCompany() {
        return taxesCompany;
    }

    public void setTaxesCompany(Taxes taxesCompany) {
        this.taxesCompany = taxesCompany;
    }

  
    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 String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

    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<Taxes> getTaxesPending() {
        return taxesPending;
    }

    public void setTaxesPending(List<Taxes> taxesPending) {
        this.taxesPending = taxesPending;
    }
    
    

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