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.ProductBrandController;
import com.arrebol.taxiservicios.controller.catalog.ProductController;
import com.arrebol.taxiservicios.controller.stocktaking.InvoiceController;
import com.arrebol.taxiservicios.controller.stocktaking.TransferStocktakingController;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.Brand;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.catalog.Product;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.core.User;
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.InvoiceHasProductId;
import com.arrebol.taxiservicios.model.stocktaking.TransferStocktaking;
import com.arrebol.taxiservicios.model.stocktaking.TransferStocktakingHasProduct;
import com.arrebol.taxiservicios.model.stocktaking.TransferStocktakingHasProductId;
import com.arrebol.taxiservicios.services.catalog.ProductService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
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 @author Oscar Vargas
 */
@Named
@ViewScoped
public class TransferStocktakingAddBean extends TaxiGenericBean implements Serializable, Datatable {

    /**
     *
     */
    public void createNewProduct() {
        try {
            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;
        }
            getNewProduct().setAmount(0d);
            getNewProduct().setAmount2(0d);
            getNewProduct().setQuantity(0);
            getNewProduct().setQuantity2(0);
            getNewProduct().setUtility(0d);
            getNewProduct().setUtility2(0d);
            getNewProduct().setService(BasicType.DISABLED);
            getNewProduct().setActiveStatus(BasicType.ENEBLED);

            if (productCtrl.saveProduct(getNewProduct(), getLoggedUser().getId(), getBrandId())) {
                logger.info("createNewProduct");
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Transferencia de inventario",
                        getBundlePropertyFile().getString("invoice.add.new.product.success.desc"));

                setExistingProducts(null);
            } else {
                logger.info("Error createNewProduct");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Transferencia de inventario",
                        getBundlePropertyFile().getString("invoice.add.new.product.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("createNewProduct: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    "Transferencia de inventario",
                    getBundlePropertyFile().getString("invoice.add.new.product.exception.desc"));
        }

        setNewProduct(null);
    }

    /**
     * Save or update a Transfer and It's product list.
     */
    public void saveUpdate() {
        logger.info("saveUpdate");
        boolean success = false;
        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().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden eliminar más registros porque ya existe un cuadre de caja general del día");
                return;
            }
        User by = new User(getLoggedUser().getId(), "");

        try {

            if (isAddInvoiceBtnOnclick()) {
                setTransferId(UUID.randomUUID().toString());

                getTransfer().setId(getTransferId());
                getTransfer().setActive(true);
                getTransfer().setCreatedBy(by);
                getTransfer().setTransferLocation(new Location(locationId));
                getTransfer().setLocation(getLoggedUser().getLocation());
                getTransfer().setStatusType(StatusType.APPROVED);
                getTransfer().setCreatedOn(new Date());

                success = getController()
                        .save(getTransfer(), fillTransferProducts(by));
            }

            if (success) {
                String title = isAddInvoiceBtnOnclick() ? "invoice.add.title" : "invoice.edit.title";
                String message = isAddInvoiceBtnOnclick() ? "invoice.add.success.desc" : "invoice.edit.success.desc";
                setAddInvoiceBtnOnclick(false);
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Guardar transferencia",
                        "Se registró correctamente");
            } else {
                logger.error("Transfer " + getTransfer() + " was not " + (isAddInvoiceBtnOnclick() ? "updated" : "saved"));
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Guardar transferencia",
                        "No se pudo guardar la transferencia de inventario");
            }
        } catch (Exception e) {
            logger.error("saveUpdate: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    "Guardar transferencia",
                    "Ocurrió un error la guardar la transferencia de inventario");
        }
    }

    /**
     * Delete the selected product from a Invoice's product list.
     */
    public void deleteSelectedProduct() {
        logger.info("deleteSelectedProduct");
        try {
            if (!isAddInvoiceBtnOnclick()) {

            }
            getTransferProducts().remove(getSelectedProduct());

        } catch (Exception e) {
            logger.error("deleteSelectedProduct", e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("garage.title"),
                    getBundlePropertyFile().getString("fatal.access.details"));
        }
    }

    /**
     * Fill list of Invoice's products.
     *
     * @param by Created/Updated user.
     * @return List of products to be saved for Invoice.
     */
    private List<TransferStocktakingHasProduct> fillTransferProducts(User by) {
        List<TransferStocktakingHasProduct> transferStocktakingHasProduct = new ArrayList<>();

        getTransferProducts().forEach((Product prdct) -> {
            transferStocktakingHasProduct.add(
                    new TransferStocktakingHasProduct(
                            new TransferStocktakingHasProductId(getTransferId(), prdct.getId()),
                            prdct.getAmount().floatValue(), prdct.getQuantity(),
                            by, new Date()
                    )
            );
        });

        return transferStocktakingHasProduct;
    }

    private static final long serialVersionUID = -2908972533530111320L;

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

    private TransferStocktakingController controller;
    private GenericValidationController genericController;
    private TransferStocktaking transfer;
    private List<TransferStocktakingHasProduct> details;
    private List<Product> transferProducts;
    private List<Product> oldTransferProducts;
    private Product selectedProduct;
    private Product product;
    private String locationId;
    private boolean addInvoiceBtnOnclick;
    private String transferId;
    private TransferStocktakingHasProduct selectedDetail;
    private String productId;
    private Integer quantity;
    private Float price;
    private Float priceMayoreo;
    private Float subTotal;
    private Float totalIva;
    private Float total;
    private List<Product> existingProducts;
    private boolean activeIVA;
    private Product newProduct;
    private String brandId;
    
    private String taxiId;
    private ProductBrandController brandCtrl;
    private ProductController productCtrl;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            setTransfer(new TransferStocktaking());
            brandCtrl = new ProductBrandController();
            productCtrl = new ProductController();
            setController(new TransferStocktakingController());
            setGenericController(new GenericValidationController());
            setAddInvoiceBtnOnclick(true);
        } catch (Exception e) {
            logger.error("Can not load the add view for Invoice", e);
        }
    }

    public String getTaxiId() {
        return taxiId;
    }

    public void setTaxiId(String taxiId) {
        this.taxiId = taxiId;
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public TransferStocktakingHasProduct getSelectedDetail() {
        return selectedDetail;
    }

    public void setSelectedDetail(TransferStocktakingHasProduct selectedDetail) {
        this.selectedDetail = selectedDetail;
    }

    public String getTransferId() {
        return transferId;
    }

    public void setTransferId(String transferId) {
        this.transferId = transferId;
    }

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

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

    public String getLocationId() {
        return locationId;
    }

    public void setLocationId(String locationId) {
        this.locationId = locationId;
    }

    public TransferStocktakingController getController() {
        return controller;
    }

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

    public TransferStocktaking getTransfer() {
        return transfer;
    }

    public void setTransfer(TransferStocktaking transfer) {
        this.transfer = transfer;
    }

    public void setAddInvoiceBtnOnclick(boolean addInvoiceBtnOnclick) {
        this.addInvoiceBtnOnclick = addInvoiceBtnOnclick;
    }

    public boolean isAddInvoiceBtnOnclick() {
        return addInvoiceBtnOnclick;
    }

    public List<Location> getLocations() {
        return getController().fillLocationComboBox();
    }

    public List<Product> getExistingProducts() {
        if (null == existingProducts) {
            existingProducts = getController().fillProductsComboBox();
        }
        return existingProducts;

    }

    public void setExistingProducts(List<Product> existingProducts) {
        this.existingProducts = existingProducts;
    }

    public List<Product> getTransferProducts() {
        if (null == transferProducts) {
            transferProducts = new ArrayList<>();
        }
        return transferProducts;
    }

    public List<Product> getOldTransferProducts() {
        if (null == oldTransferProducts) {
            oldTransferProducts = new ArrayList<>();
        }
        return oldTransferProducts;
    }

    public Product getSelectedProduct() {
        return selectedProduct;
    }

    public void setSelectedProduct(Product selectedProduct) {
        this.selectedProduct = selectedProduct;
    }

    public Float getSubTotal() {
        return subTotal;
    }

    public void setSubTotal(Float subTotal) {
        this.subTotal = subTotal;
    }

    public Float getTotalIva() {
        return totalIva;
    }

    public void setTotalIva(Float totalIva) {
        this.totalIva = totalIva;
    }

    public Float getTotal() {
        return total;
    }

    public void setTotal(Float total) {
        this.total = total;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public boolean isActiveIVA() {
        return activeIVA;
    }

    public void setActiveIVA(boolean activeIVA) {
        this.activeIVA = activeIVA;
    }

    public Product getNewProduct() {
        if (null == newProduct) {
            newProduct = new Product();
        }

        return newProduct;
    }

    public void setNewProduct(Product newProduct) {
        this.newProduct = newProduct;
    }

    public List<Brand> getBrandes() {
        return brandCtrl.fillProductBrandComboBox();
    }

    public String getBrandId() {
        return brandId;
    }

    public void setBrandId(String brandId) {
        this.brandId = brandId;
    }

    public Float getPriceMayoreo() {
        return priceMayoreo;
    }

    public void setPriceMayoreo(Float priceMayoreo) {
        this.priceMayoreo = priceMayoreo;
    }

    @Override
    public void editRow(RowEditEvent event) {
        try {
            Product p = (Product) event.getObject();

            getTransferProducts().forEach((Product comboProduct) -> {
                if (p.getId().equals(comboProduct.getId())) {
                    comboProduct.setQuantity(p.getQuantity());
                    comboProduct.setAmount(p.getAmount());
                    comboProduct.setUtility(p.getUtility());
                }
            });

        } catch (Exception e) {
            logger.error("editRow: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL, "Compras",
                    "Error al editar el producto");
        }

    }

    @Override
    public void onRowCancel(RowEditEvent event) {
    }

    @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 addRow() {
        logger.info("addRow for INVOICEHASPRODUCT");

        try {
            Product prod = new Product(productId, price.doubleValue(), quantity);
            Product tmpProduct = findProduct(productId);
            prod.setCode(tmpProduct.getCode());
            prod.setName(tmpProduct.getName());

            getTransferProducts().add(prod);

            productId = null;
            price = null;
            quantity = null;
        } catch (Exception e) {
            logger.error("addRow for INVOICEHASPRODUCT: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("invoice.detail.add.title"),
                    getBundlePropertyFile().getString("invoice.detail.add.exception.desc"));
        }
    }

    public Product findProduct(String id) {
        for (Product prod : getExistingProducts()) {
            if (id.equals(prod.getId())) {
                return prod;
            }
        }
        return null;
    }

    @Override
    public void deleteRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
