package com.arrebol.taxiservicios.beans.stocktaking.invoice;

import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.stocktaking.InvoiceController;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.stocktaking.Invoice;
import com.arrebol.taxiservicios.model.stocktaking.InvoiceHasProduct;
import java.io.Serializable;
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;

/**
 *
 * @author Carlos Janitzio Zavala López.
 */
@Named
@ViewScoped
public class InvoiceUpdateBean extends TaxiGenericBean implements Serializable {

    /**
     * Update the invoice details.
     */
    public void updateInvoice() {
        logger.info("updateInvoice");
        User by = new User(getLoggedUser().getId(), "");
        if(getGenericController().existCheckStocktakingPending(getLoggedUser().getLocation().getId()))
        {
            showMessage(FacesMessage.SEVERITY_WARN,
                        "Inventario cerrado",
                        "No puedes hacer ningun movimiento al inventario hasta que se termine de cotejar");
            return;
        }
        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(getGenericController().existStableSmallBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja chica del día");
                return;
            }
            if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja general del día");
                return;
            }

        try {
            getInvoice().setPerson(new Person(providerId));
            getInvoice().setLastUpdatedBy(by);
            getInvoice().setLastUpdatedOn(new Date());

            boolean success = getController().updateInvoice(getInvoice());

            if (success) {
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("invoice.edit.title"),
                        getBundlePropertyFile().getString("invoice.edit.success.desc"));
            } else {
                logger.error("Invoice " + getInvoice() + " was not updated");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("invoice.edit.title"),
                        getBundlePropertyFile().getString("invoice.detail.update.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("updateInvoice: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("invoice.edit.title"),
                    getBundlePropertyFile().getString("invoice.update.exception.desc"));
        }
    }

    private static final long serialVersionUID = -363495321297989468L;

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

    private InvoiceController controller;
    private GenericValidationController genericController;
    private Invoice invoice;
    private List<InvoiceHasProduct> details;
    private String providerId;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            String id = externalContext().getRequestParameterMap().get("invoiceForm:invoiceDtTbl_selection");
            setController(new InvoiceController());
            setGenericController(new GenericValidationController());
            setInvoice(getController().loadInvoicebyId(id));
            setDetails(getController().fillInvoiceHasProductDatatable(id));
            setProviderId(getInvoice().getPerson().getId());
        } catch (Exception e) {
            logger.error("Can not load the update view for Invoice", e);
        }
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public InvoiceController getController() {
        return controller;
    }

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

    public Invoice getInvoice() {
        return invoice;
    }

    public void setInvoice(Invoice invoice) {
        this.invoice = invoice;
    }

    public List<InvoiceHasProduct> getDetails() {
        return details;
    }

    public void setDetails(List<InvoiceHasProduct> details) {
        this.details = details;
    }

    public String getProviderId() {
        return providerId;
    }

    public void setProviderId(String providerId) {
        this.providerId = providerId;
    }

    public List<Person> getProviders() {
        return getController().fillProviderComboBox();
    }

}
