/*
 * 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.ReturnInvoiceController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.stocktaking.Invoice;
import com.arrebol.taxiservicios.model.stocktaking.InvoiceHasProduct;
import com.arrebol.taxiservicios.model.stocktaking.ReturnInvoice;
import java.io.Serializable;
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.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 ReturnInvoiceBean extends TaxiGenericBean implements Serializable, Datatable {
    
    public List<InvoiceHasProduct> getDetailsInvoice(String id) {
        logger.info("getDetailsInvoice");
        try {
            setDetailsinvoice(getController().findAllProductByInvoiceId(id));

            logger.info("detailsInvoice loaded size " + detailsinvoice.size());
        } catch (Exception e) {
            logger.error("getDetailsInvoice", e);
        }
        return null == detailsinvoice ? new ArrayList<>() : detailsinvoice;
    }
    
    public void fillDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setReturnInvoice(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().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;
            }
        
        
        ReturnInvoice obj = new ReturnInvoice();
        obj.setActive(Boolean.TRUE);
        obj.setCreatedBy(getLoggedUser());
        obj.setCreatedOn(new Date());
        obj.setId(UUID.randomUUID().toString());
        obj.setLocation(getLoggedUser().getLocation());
        obj.setDescription(comments);
        Invoice inv = getController().findInvoiceById(invoiceId);
        obj.setReturnPayment(inv.getTotal());
        obj.setInvoice(inv);
        
        if(getController().saveReturnInvoice(obj, getController().getProductsByInvoice(inv)))
        {
            showMessage(FacesMessage.SEVERITY_INFO,
                        "Devolución",
                        "Se creó exitosamente");
        }
        else
        {
            showMessage(FacesMessage.SEVERITY_ERROR,
                        "Devolución",
                        "Ocurrió un problema, no se guardo la devolución");
        }
        
    }

    @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() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

    }
    
    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setController(new ReturnInvoiceController());
            setGenericController(new GenericValidationController());
            setReturnInvoice(getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation()));
            setInvoice(getController().fillInvoiceByLocation(getLoggedUser().getLocation()));

            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(ReturnInvoiceBean.class);
    ReturnInvoiceController controller;
    GenericValidationController genericController;
    private Date startDate;
    private Date endDate;
    private List<ReturnInvoice> returnInvoice;
    private List<Invoice> invoice;
    private String invoiceId;
    private String comments;
    private ReturnInvoice selectedReturnInvoice;
    private List<InvoiceHasProduct> detailsinvoice;

    public ReturnInvoiceController getController() {
        return controller;
    }

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

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    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<ReturnInvoice> getReturnInvoice() {
        return returnInvoice;
    }

    public void setReturnInvoice(List<ReturnInvoice> returnInvoice) {
        this.returnInvoice = returnInvoice;
    }

    public ReturnInvoice getSelectedReturnInvoice() {
        return selectedReturnInvoice;
    }

    public void setSelectedReturnInvoice(ReturnInvoice selectedReturnInvoice) {
        this.selectedReturnInvoice = selectedReturnInvoice;
    }

    public List<Invoice> getInvoice() {
        return invoice;
    }

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

    public String getInvoiceId() {
        return invoiceId;
    }

    public void setInvoiceId(String invoiceId) {
        this.invoiceId = invoiceId;
    }

    public String getComments() {
        return comments;
    }

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

    public List<InvoiceHasProduct> getDetailsinvoice() {
        return detailsinvoice;
    }

    public void setDetailsinvoice(List<InvoiceHasProduct> detailsinvoice) {
        this.detailsinvoice = detailsinvoice;
    }
    
    
}
