/*
 * 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.ProductController;
import com.arrebol.taxiservicios.controller.stocktaking.KardexInStocktakingController;
import com.arrebol.taxiservicios.controller.stocktaking.StocktakingMovementsController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.catalog.Product;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.StocktakingType;
import com.arrebol.taxiservicios.model.stocktaking.StocktakingMovements;
import com.arrebol.taxiservicios.model.stocktaking.view.KardexInStocktakingView;
import java.io.Serializable;
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
 */
@Named
@ViewScoped
public class StocktakingMovementsBean extends TaxiGenericBean implements Serializable, Datatable {

    public void fillDataTableBetweenDates() {
        try {
            if (getGenericStartDate().after(getGenericEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                if(getKardex() != null)
                    getKardex().clear();
                
                setKardex(getController().fillDataTableBetweenDates(getGenericStartDate(), getGenericEndDate(), getLoggedUser().getLocation()));
                
                calcularTotales();
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    
    @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) {
        showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1));
    }

    @Override
    public void addRow() {
        
        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;
            }

        getStocktaking().setActiveStatus(BasicType.ENEBLED);
        getStocktaking().setCreatedBy(getLoggedUser());
        getStocktaking().setCreatedOn(new Date());
        getStocktaking().setId(UUID.randomUUID().toString());
        getStocktaking().setProduct(new Product(productId));
        getStocktaking().setLocation(getLoggedUser().getLocation());
        if(tipo.equalsIgnoreCase("IN"))
            getStocktaking().setTypeMovement(StocktakingType.IN);
        if(tipo.equalsIgnoreCase("OUT"))
            getStocktaking().setTypeMovement(StocktakingType.OUT);
        if(getController().save(stocktaking))
        {
            Product tmp = getProductController().findProductById(productId);
            
            if(getLoggedUser().getLocation().getId().equalsIgnoreCase("4d0859be-e31a-4acb-a690-2a5c2cb027a7"))
            {
                if(getStocktaking().getTypeMovement() == StocktakingType.IN)
                tmp.setQuantity(tmp.getQuantity() + getStocktaking().getQuantity());
                if(getStocktaking().getTypeMovement() == StocktakingType.OUT)
                tmp.setQuantity(tmp.getQuantity() - getStocktaking().getQuantity());
            }
            else
            {
                if(getStocktaking().getTypeMovement() == StocktakingType.IN)
                tmp.setQuantity2(tmp.getQuantity2() + getStocktaking().getQuantity());
                if(getStocktaking().getTypeMovement() == StocktakingType.OUT)
                tmp.setQuantity2(tmp.getQuantity2() - getStocktaking().getQuantity());
            }
            
            
            getProductController().saveProduct(tmp, getLoggedUser().getId(), tmp.getBrand().getId());
            
            showMessage(FacesMessage.SEVERITY_INFO,
                        "Registro guardado",
                        "Se registro y actualizó el inventario satisfactoriamente");
        }
    }

    @Override
    public void deleteRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
    public void calcularTotales(){
        
       totalIn = 0;
       totalOut = 0;
       for(StocktakingMovements temp : kardex)
       {
           if(temp.getTypeMovement() == StocktakingType.IN)
           {
               totalIn += temp.getQuantity();
           }
           else
           {
               totalOut += temp.getQuantity();
           }
       }
    }
    
    final Logger logger = LogManager.getLogger(StocktakingMovementsBean.class);
    StocktakingMovementsController controller;
    ProductController productController;
    private Date startDate;
    private Date endDate;
    private List<StocktakingMovements> kardex;
    private int totalIn;
    private int totalOut;
    private StocktakingMovements stocktaking;
    private List<Product> products;
    private String productId;
    private String tipo;
    private GenericValidationController genericController;
    
    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            setGenericUpDates(true);
            stocktaking = new StocktakingMovements();
            setController(new StocktakingMovementsController());
            setProductController(new ProductController());
            setGenericController(new GenericValidationController());
            
            setKardex(getController().fillDataTableBetweenDates(getGenericStartDate(),
                    getGenericEndDate(), getLoggedUser().getLocation()));
            setProducts(getProductController().fillProductDatatable());
            
            calcularTotales();

            logger.info("StocktakingMovements loaded");
        } catch (Exception e) {
            logger.error("init", e);
        }
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public String getTipo() {
        return tipo;
    }

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

    public String getProductId() {
        return productId;
    }

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

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public ProductController getProductController() {
        return productController;
    }

    public void setProductController(ProductController productController) {
        this.productController = productController;
    }

    public StocktakingMovements getStocktaking() {
        return stocktaking;
    }

    public void setStocktaking(StocktakingMovements stocktaking) {
        this.stocktaking = stocktaking;
    }

    public StocktakingMovementsController getController() {
        return controller;
    }

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

    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<StocktakingMovements> getKardex() {
        return kardex;
    }

    public void setKardex(List<StocktakingMovements> kardex) {
        this.kardex = kardex;
    }

    public int getTotalIn() {
        return totalIn;
    }

    public void setTotalIn(int totalIn) {
        this.totalIn = totalIn;
    }

    public int getTotalOut() {
        return totalOut;
    }

    public void setTotalOut(int totalOut) {
        this.totalOut = totalOut;
    }
    
}
