/*
 * 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.DriverController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.catalog.ProductController;
import com.arrebol.taxiservicios.controller.stocktaking.CheckStocktakingController;
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.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.CheckStatus;
import com.arrebol.taxiservicios.model.enums.PersonType;
import com.arrebol.taxiservicios.model.enums.StocktakingType;
import com.arrebol.taxiservicios.model.stocktaking.CheckStocktaking;
import com.arrebol.taxiservicios.model.stocktaking.CheckStocktakingDetail;
import com.arrebol.taxiservicios.model.stocktaking.StocktakingMovements;
import com.arrebol.taxiservicios.model.view.PersonListView;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Font;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
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 CheckStocktakingDetailBean extends TaxiGenericBean implements Serializable, Datatable {
    
    public void editRow(RowEditEvent event) {
        CheckStocktakingDetail pro = (CheckStocktakingDetail) event.getObject();
        if (pro != null) {
            getController().updateDetailById(pro, getLoggedUser());

            getCheckStocktaking().clear();
            setCheckStocktaking(getController().findDetailsFromCheckStocktakingID(new CheckStocktaking(getCheckId())));

            showMessage(FacesMessage.SEVERITY_INFO, "Registro Editado", "Se hizo el cambio correctamente.");
        }
    }

    @Override
    public void onRowCancel(RowEditEvent event) {
        showMessage(FacesMessage.SEVERITY_INFO, "Edición Cancelada", ((CheckStocktakingDetail) event.getObject()).getProduct().getName());
    }
    
    @Override
    public void addRow() {
        setValidarStatus("true");
        if(getSelectedStocktaking().getCheckStatus().equals(CheckStatus.PENDING)){
            
            if(getController().updateById(getCheckId(), CheckStatus.FINISH, getLoggedUser(), getIdPersonEjecutor(), getIdPersonRevisor()));
            {
                getCheckStocktaking().clear();
                setCheckStocktaking(getController().findDetailsFromCheckStocktakingID(new CheckStocktaking(getCheckId())));
                for(CheckStocktakingDetail products : getCheckStocktaking())
                {
                    if((products.getNewStocktaking() - products.getLastStocktaking()) > 0)
                    {
                        StocktakingMovements stock = new StocktakingMovements();
                        stock.setId(UUID.randomUUID().toString());
                        stock.setActiveStatus(BasicType.ENEBLED);
                        stock.setComments(products.getDescription());
                        stock.setCreatedBy(getLoggedUser());
                        stock.setCreatedOn(new Date());
                        stock.setLocation(getLoggedUser().getLocation());
                        stock.setProduct(products.getProduct());
                        stock.setQuantity(Math.abs(products.getNewStocktaking() - products.getLastStocktaking()));
                        stock.setTypeMovement(StocktakingType.IN);

                        if(getStockController().save(stock))
                        {
                            Product prd = getProductController().findProductById(products.getProduct().getId());

                            if(getLoggedUser().getLocation().getId().equalsIgnoreCase("4d0859be-e31a-4acb-a690-2a5c2cb027a7"))
                            {
                                prd.setQuantity(prd.getQuantity() + stock.getQuantity());

                            }
                            else
                            {
                                prd.setQuantity2(prd.getQuantity2() + stock.getQuantity());

                            }

                            getProductController().saveProduct(prd, getLoggedUser().getId(), "nada");
                        }
                    }

                    if((products.getNewStocktaking() - products.getLastStocktaking()) < 0)
                    {
                        StocktakingMovements stock = new StocktakingMovements();
                        stock.setId(UUID.randomUUID().toString());
                        stock.setActiveStatus(BasicType.ENEBLED);
                        stock.setComments(products.getDescription());
                        stock.setCreatedBy(getLoggedUser());
                        stock.setCreatedOn(new Date());
                        stock.setLocation(getLoggedUser().getLocation());
                        stock.setProduct(products.getProduct());
                        stock.setQuantity(Math.abs(products.getNewStocktaking() - products.getLastStocktaking()));
                        stock.setTypeMovement(StocktakingType.OUT);

                        if(getStockController().save(stock))
                        {
                            Product prd = getProductController().findProductById(products.getProduct().getId());

                            if(getLoggedUser().getLocation().getId().equalsIgnoreCase("4d0859be-e31a-4acb-a690-2a5c2cb027a7"))
                            {
                                prd.setQuantity(prd.getQuantity() - stock.getQuantity());
                            }
                            else
                            {

                                prd.setQuantity2(prd.getQuantity2() - stock.getQuantity());
                            }


                            getProductController().saveProduct(prd, getLoggedUser().getId(), "nada");
                        }
                    }
                }

                showMessage(FacesMessage.SEVERITY_INFO,
                            "Registro guardado",
                            "Se registro y actualizó el inventario satisfactoriamente");
            }
        }else{
            showMessage(FacesMessage.SEVERITY_INFO,
                            "Error",
                            "Este inventario ya fue registrado");
        }
    }

    @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() {    
        
    }
    
    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            setController(new CheckStocktakingController());
            setGenericController(new GenericValidationController());
            setStockController(new StocktakingMovementsController());
            setProductController(new ProductController());
            setCheckId(externalContext().getRequestParameterMap().get("selectedId"));
            setSelectedStocktaking(getController().findById(getCheckId()));
            setCheckStocktaking(getController().findDetailsFromCheckStocktakingID(new CheckStocktaking(getCheckId())));
            setDriverController(new DriverController());
            setEmployees(getDriverController().findListOfPersonsByType(PersonType.EMPLOYEE, getLoggedUser().getLocation()));
            setValidarStatus("false");
            logger.info("Return CheckStocktaking loaded");
        } catch (Exception e) {
            logger.error("init", e);
        }
    }
    
    final Logger logger = LogManager.getLogger(CheckStocktakingDetailBean.class);
    CheckStocktakingController controller;
    StocktakingMovementsController stockController;
    ProductController productController;
    private List<CheckStocktakingDetail> checkStocktaking;
    private CheckStocktakingDetail selectedCheckStocktaking;
    private CheckStocktaking selectedStocktaking;
    private GenericValidationController genericController;
    private String checkId;
    private String idPersonEjecutor;
    private String idPersonRevisor;
    private String validarStatus;
    private List<PersonListView> employees;
    private DriverController driverController;

    public DriverController getDriverController() {
        return driverController;
    }

    public void setDriverController(DriverController driverController) {
        this.driverController = driverController;
    }

    public ProductController getProductController() {
        return productController;
    }

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

    public StocktakingMovementsController getStockController() {
        return stockController;
    }

    public void setStockController(StocktakingMovementsController stockController) {
        this.stockController = stockController;
    }

    public String getCheckId() {
        return checkId;
    }

    public void setCheckId(String checkId) {
        this.checkId = checkId;
    }

   
    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public CheckStocktakingController getController() {
        return controller;
    }

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

    public List<CheckStocktakingDetail> getCheckStocktaking() {
        return checkStocktaking;
    }

    public void setCheckStocktaking(List<CheckStocktakingDetail> checkStocktaking) {
        this.checkStocktaking = checkStocktaking;
    }

    public CheckStocktakingDetail getSelectedCheckStocktaking() {
        return selectedCheckStocktaking;
    }

    public void setSelectedCheckStocktaking(CheckStocktakingDetail selectedCheckStocktaking) {
        this.selectedCheckStocktaking = selectedCheckStocktaking;
    }

    public String getIdPersonEjecutor() {
        return idPersonEjecutor;
    }

    public void setIdPersonEjecutor(String idPersonEjecutor) {
        this.idPersonEjecutor = idPersonEjecutor;
    }

    public String getIdPersonRevisor() {
        return idPersonRevisor;
    }

    public void setIdPersonRevisor(String idPersonRevisor) {
        this.idPersonRevisor = idPersonRevisor;
    }

    public List<PersonListView> getEmployees() {
        return employees;
    }

    public void setEmployees(List<PersonListView> employees) {
        this.employees = employees;
    }

    public CheckStocktaking getSelectedStocktaking() {
        return selectedStocktaking;
    }

    public void setSelectedStocktaking(CheckStocktaking selectedStocktaking) {
        this.selectedStocktaking = selectedStocktaking;
    }

    public String getValidarStatus() {
        return validarStatus;
    }

    public void setValidarStatus(String validarStatus) {
        this.validarStatus = validarStatus;
    }

}
