/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arrebol.taxiservicios.beans.stocktaking.invoice;

import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
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.stocktaking.InvoiceController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
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.StatusType;
import com.arrebol.taxiservicios.model.stocktaking.Invoice;
import com.arrebol.taxiservicios.model.stocktaking.InvoiceHasProduct;
import com.arrebol.taxiservicios.model.stocktaking.ProductInvoiceBk;
import com.arrebol.taxiservicios.model.stocktaking.view.StocktakingInvoiceView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
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.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author oscarvargas
 */
@Named
@ViewScoped
public class InvoiceListBean extends TaxiGenericBean implements Serializable, Datatable {

    public List<InvoiceHasProduct> getDetailsInvoice(String id) {
        logger.info("getDetailsInvoice");
        try {
            setDetailsinvoice(getController().findAllProductByInvoiceId(id));

            logger.info("detailsInvoice loaded size " + detailsinvoice.size());
        } catch (Exception e) {
            logger.error("getDetailsInvoice", e);
        }
        return null == detailsinvoice ? new ArrayList<>() : detailsinvoice;
    }
    
    public void authorize() {
        logger.info("autorizado");
        User by = new User(getLoggedUser().getId(), "");
        try {
            if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Error","No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            if (getController().authorizeInvoice(selectedInvoice, by)) {
                setSelectedInvoice(null);
                showMessage(FacesMessage.SEVERITY_INFO, "Mensaje","Compra autorizada");
                init();
            } else {
                logger.error("Invoice " + getSelectedInvoice() + "can not be updated");
                showMessage(FacesMessage.SEVERITY_WARN, "Error","No se pudo autorizar la compra");
            }

        } catch (Exception e) {
            logger.error("editRow: " + e);
            
        }
    }
    
    public void authorizeDeposit() {
        logger.info("autorizadeDeposit");
        User by = new User(getLoggedUser().getId(), "");
        try {
            if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Error","No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            if (getController().authorizeInvoiceDeposit(selectedInvoicePending, by)) {
                
                BankCardKardex bankCardKardexObj = new BankCardKardex();
                

                bankCardKardexObj.setBankCard(getSelectedInvoicePending().getBankCard());
                bankCardKardexObj.setAmount(getSelectedInvoicePending().getTotal().doubleValue());
                bankCardKardexObj.setAmountBefore(getSelectedInvoicePending().getBankCard().getBalance());
                bankCardKardexObj.setAmountAfter(bankCardKardexObj.getAmountBefore()-bankCardKardexObj.getAmount());
                bankCardKardexObj.setKardexType(BankCardKardexType.EXPENSE);
                bankCardKardexObj.setDescription("Compra de inventario");
                bankCardKardexObj.setLocation(getSelectedInvoicePending().getLocation());
                
                BankCardKardexController bankCardKardexCtrl = new BankCardKardexController(); 
                bankCardKardexCtrl.save(bankCardKardexObj, getLoggedUser().getId());

                BankCard bankCard = getSelectedInvoicePending().getBankCard();
                
                bankCard.setBalance(bankCardKardexObj.getAmountAfter());
                
                BankCardController bankCardCtrl = new BankCardController();
                
                bankCardCtrl.save(bankCard, getLoggedUser().getId());
                
                setSelectedInvoicePending(null);
                showMessage(FacesMessage.SEVERITY_INFO, "Mensaje","Compra autorizada");
               setInvoicePending(getController().fillDataTableDepositPending(getLoggedUser().getLocation().getId()));
            } else {
                logger.error("Invoice " + getSelectedInvoice() + "can not be updated");
                showMessage(FacesMessage.SEVERITY_WARN, "Error","No se pudo autorizar la compra");
            }

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

    public void fillDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setInvoice(getController().fillDataTableBetweenDates(getStartDate(), getEndDate()));
                totalizador();
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    /**
     *
     * @param economicNumber
     * @return
     */
    public List<String> autoCompleVehicle(String economicNumber) {
        try {
            return getController().autoCompleVehicle("%" + economicNumber + "%");
        } catch (Exception e) {
            logger.error("autoCompleVehicle", e);

            return new ArrayList<>();
        }
    }

    /**
     *
     * @param event
     */
    public void onAutoCompleteItemSelect(SelectEvent event) {
        try {
            setInvoice(getController().findAllInvoicesByEconomicNumber((String) event.getObject()));
        } catch (Exception e) {
            logger.error("onAutoCompleteItemSelect", e);
        }
    }

    /**
     * Edit invoice by selection datatable.
     *
     * @param outcome path for invoice update.
     * @return URL for updagte invoice.
     */
    public String editInvoice(String outcome) {
        return outcome;
    }

    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 addRow() {
        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 deleteRow() {
        logger.info("deleteRow");
        try {
            if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            List<ProductInvoiceBk> invoiceBks = getController().seachInvoiceInBackupById(getSelectedInvoice().getId());

            if (invoiceBks.isEmpty()) {
                logger.error("Invoice " + getSelectedInvoice() + " unauthorized action.");
                showMessage(FacesMessage.SEVERITY_WARN,
                        getBundlePropertyFile().getString("invoice.delete.title"),
                        getBundlePropertyFile().getString("invoice.delete.cannot.deleted.desc"));
            } else {
                if (getController().deleteInvoiceById(getSelectedInvoice().getId(), invoiceBks)) {
                    getInvoice().remove(getSelectedInvoice());
                    setSelectedInvoice(null);

                    showMessage(FacesMessage.SEVERITY_INFO,
                            getBundlePropertyFile().getString("invoice.delete.title"),
                            getBundlePropertyFile().getString("invoice.delete.success.desc"));
                } else {
                    logger.error("Invoice " + getSelectedInvoice() + "can not be deleted");
                    showMessage(FacesMessage.SEVERITY_WARN,
                            getBundlePropertyFile().getString("invoice.delete.title"),
                            getBundlePropertyFile().getString("invoice.delete.exception.desc"));
                }
            }
        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("invoice.delete.title"),
                    getBundlePropertyFile().getString("invoice.delete.exception.desc"));
        }
    }

    private static final long serialVersionUID = -4475615978271025834L;

    final Logger logger = LogManager.getLogger(InvoiceListBean.class);

    InvoiceController controller;
    GenericValidationController genericController;
    private List<StocktakingInvoiceView> invoice;
    private List<Invoice> invoicePending;
    private StocktakingInvoiceView selectedInvoice;
    private Invoice selectedInvoicePending;
    private String selectedItem;
    private Date startDate;
    private Date endDate;
    private List<InvoiceHasProduct> detailsinvoice;
    private float totalInvoice;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setController(new InvoiceController());
            setGenericController(new GenericValidationController());
            setInvoice(getController().fillDataTableBetweenDates(getStartDate(), getEndDate()));
            setInvoicePending(getController().fillDataTableDepositPending(getLoggedUser().getLocation().getId()));
            totalizador();
            logger.info("Invoices loaded");
        } catch (Exception e) {
            logger.error("init", e);
        }
    }

    public void totalizador() {
        totalInvoice = 0F;

        if (getInvoice() != null && !getInvoice().isEmpty()) {
            for (StocktakingInvoiceView temp : getInvoice()) {
                if(temp.getAuthorize() == StatusType.APPROVED){
                    totalInvoice += temp.getTotal();
                }      
            }
        }

    }

    public float getTotalInvoice() {
        return totalInvoice;
    }

    public void setTotalInvoice(float totalInvoice) {
        this.totalInvoice = totalInvoice;
    }

    private void initOneWeekBeforeToCurrdate() {
        try {
            Calendar start = Calendar.getInstance();

            start.set(Calendar.WEEK_OF_YEAR, start.get(Calendar.WEEK_OF_YEAR) - 1);
            start.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

            setStartDate(start.getTime());
            setEndDate(DateWrapper.getTodayMXTime());
        } catch (Exception e) {

        }
    }

    public List<InvoiceHasProduct> getDetailsinvoice() {
        return detailsinvoice;
    }

    public void setDetailsinvoice(List<InvoiceHasProduct> detailsinvoice) {
        this.detailsinvoice = detailsinvoice;
    }

    public InvoiceController getController() {
        return controller;
    }

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

    public List<StocktakingInvoiceView> getInvoice() {
        if (null == invoice) {
            invoice = new ArrayList<>();
        }
        return invoice;
    }

    public StocktakingInvoiceView getSelectedInvoice() {
        return selectedInvoice;
    }

    public void setInvoice(List<StocktakingInvoiceView> invoice) {
        this.invoice = invoice;
    }

    public void setSelectedInvoice(StocktakingInvoiceView selectedInvoice) {
        this.selectedInvoice = selectedInvoice;
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public String getSelectedItem() {
        return selectedItem;
    }

    public void setSelectedItem(String selectedItem) {
        this.selectedItem = selectedItem;
    }

    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 List<Invoice> getInvoicePending() {
        return invoicePending;
    }

    public void setInvoicePending(List<Invoice> invoicePending) {
        this.invoicePending = invoicePending;
    }

    public Invoice getSelectedInvoicePending() {
        return selectedInvoicePending;
    }

    public void setSelectedInvoicePending(Invoice selectedInvoicePending) {
        this.selectedInvoicePending = selectedInvoicePending;
    }

}
