/*
 * 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.stocktaking.ChangeAmountProductController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.catalog.Product;
import com.arrebol.taxiservicios.model.enums.StatusType;
import com.arrebol.taxiservicios.model.stocktaking.ChangeAmountProduct;
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 ChangeAmountProductBean extends TaxiGenericBean implements Serializable, Datatable {
    
    public void fillDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setChange(getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation()));
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    
    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() {
        
        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;
            }
        
        ChangeAmountProduct obj = new ChangeAmountProduct();
        obj.setActive(Boolean.TRUE);
        obj.setStatusType(StatusType.APPROVED);
        obj.setCreatedBy(getLoggedUser());
        obj.setCreatedOn(new Date());
        obj.setId(UUID.randomUUID().toString());
        obj.setLocation(getLoggedUser().getLocation());
        obj.setComment(comments);
        obj.setProduct(new Product(productId));
        obj.setAmount(amount);
        
        Product prod = getController().findProductById(productId);
        
        if(getLoggedUser().getLocation().getId().equalsIgnoreCase("4d0859be-e31a-4acb-a690-2a5c2cb027a7"))
            {
                obj.setLastAmount(prod.getAmount());
            }
            else
            {
                obj.setLastAmount(prod.getAmount2());
            }
        
        
        if(getController().save(obj, prod))
        {
            showMessage(FacesMessage.SEVERITY_INFO,
                        "Cambio de precio menudeo",
                        "Se creó exitosamente");
        }
        else
        {
            showMessage(FacesMessage.SEVERITY_ERROR,
                        "Cambio de precio menudeo",
                        "Ocurrió un problema, no se guardo el cambio");
        }
        
    }

    @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() {
        ChangeAmountProduct tmp = getController().findById(selectedChange.getId());
        Product prod = getController().findProductById(tmp.getProduct().getId());
        
        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;
            }
        
        if(getLoggedUser().getLocation().getId().equalsIgnoreCase("4d0859be-e31a-4acb-a690-2a5c2cb027a7"))
            {
                prod.setAmount(tmp.getLastAmount());
            }
            else
            {
                prod.setAmount2(tmp.getLastAmount());
            }
        
        if(getController().updateProductAmountById(prod))
        {
            if(getController().deleteChangeProductAmountById(tmp))
            {
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Cambio de precio menudeo",
                        "Se deshabilitó exitosamente");
            }
        }
        
        
        

    }
    
    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setController(new ChangeAmountProductController());
            setChange(getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation()));
            setProduct(getController().fillProductsComboBox());
            setGenericController(new GenericValidationController());

            logger.info("Return Invoices loaded");
        } catch (Exception e) {
            logger.error("init", e);
        }
    }
    
    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) {

        }
    }
    
    final Logger logger = LogManager.getLogger(ChangeAmountProductBean.class);
    ChangeAmountProductController controller;
    private Date startDate;
    private Date endDate;
    private List<ChangeAmountProduct> change;
    private List<Product> product;
    private String productId;
    private String comments;
    private Double amount;
    private ChangeAmountProduct selectedChange;
    private GenericValidationController genericController;

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public ChangeAmountProductController getController() {
        return controller;
    }

    public void setController(ChangeAmountProductController 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<ChangeAmountProduct> getChange() {
        return change;
    }

    public void setChange(List<ChangeAmountProduct> change) {
        this.change = change;
    }

    public String getProductId() {
        return productId;
    }

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

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public ChangeAmountProduct getSelectedChange() {
        return selectedChange;
    }

    public void setSelectedChange(ChangeAmountProduct selectedChange) {
        this.selectedChange = selectedChange;
    }

    public List<Product> getProduct() {
        return product;
    }

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

    
    
    
}
