/*
 * 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.admin.TaxiController;
import com.arrebol.taxiservicios.controller.stocktaking.InvoiceController;
import com.arrebol.taxiservicios.controller.stocktaking.TransferStocktakingController;
import com.arrebol.taxiservicios.controller.stocktaking.TransferVehicleController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.enums.StatusType;
import com.arrebol.taxiservicios.model.stocktaking.ProductInvoiceBk;
import com.arrebol.taxiservicios.model.stocktaking.TransferStocktaking;
import com.arrebol.taxiservicios.model.stocktaking.TransferVehicle;
import com.arrebol.taxiservicios.model.stocktaking.view.StocktakingInvoiceView;
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;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author oscarvargas
 */
@Named
@ViewScoped
public class TransferVehicleListBean 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 {
                setTransfer(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() {
        boolean success = false;
        
            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;
            }
        
        TransferVehicle vehicle = new TransferVehicle();
        Taxi tmp = getController().findById(taxiId);
        vehicle.setId(UUID.randomUUID().toString());
        vehicle.setActive(true);
        vehicle.setCreatedBy(getLoggedUser());
        vehicle.setOrigenLocation(tmp.getLocation());
        vehicle.setDestinoLocation(new Location(destinoId));
        vehicle.setTaxi(new Taxi(taxiId));
        vehicle.setLocation(getLoggedUser().getLocation());
        vehicle.setStatusType(StatusType.APPROVED);
        vehicle.setCreatedOn(new Date());
        vehicle.setComment(comments);
        
        success = getController()
                        .save(vehicle);
        
        if (success) {
            
            getTaxiController().updateLocationByTaxi(taxiId, destinoId);
            showMessage(FacesMessage.SEVERITY_INFO,
                        "Guardar transferencia",
                        "Se registró correctamente");
        }
        else
        {
            showMessage(FacesMessage.SEVERITY_ERROR,
                        "Guardar transferencia",
                        "No se pudo guardar la transferencia de vehiculo");
        }
    }

    @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() {
        
    }

    private static final long serialVersionUID = -4475615978271025834L;

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

    TransferVehicleController controller;
    TaxiController taxiController;
    GenericValidationController genericController;
    private List<TransferVehicle> transfer;
    private List<Location> origen;
    private List<Location> destino;
    private List<Taxi> taxi;
    private TransferVehicle selectedTransfer;
    private Date startDate;
    private Date endDate;
    private String taxiId;
    private String origenId;
    private String destinoId;
    private String comments;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setController(new TransferVehicleController());
            setGenericController(new GenericValidationController());
            setTaxiController(new TaxiController());
            setTransfer(getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation()));
            setDestino(getController().fillLocationComboBox());
            setTaxi(getController().fillVehicleComboBox());
                  

            logger.info("TransferVehicle 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) {

        }
    }

    public TransferVehicleController getController() {
        return controller;
    }

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

    public List<TransferVehicle> getTransfer() {
        if (null == transfer) {
            transfer = new ArrayList<>();
        }
        return transfer;
    }

    public TransferVehicle getSelectedTransfer() {
        return selectedTransfer;
    }

    public void setTransfer(List<TransferVehicle> transfer) {
        this.transfer = transfer;
    }

    public void setSelectedTransfer(TransferVehicle selectedTransfer) {
        this.selectedTransfer = selectedTransfer;
    }

    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<Location> getOrigen() {
        return origen;
    }

    public void setOrigen(List<Location> origen) {
        this.origen = origen;
    }

    public List<Location> getDestino() {
        return destino;
    }

    public void setDestino(List<Location> destino) {
        this.destino = destino;
    }

    public List<Taxi> getTaxi() {
        return taxi;
    }

    public void setTaxi(List<Taxi> taxi) {
        this.taxi = taxi;
    }

    public String getTaxiId() {
        return taxiId;
    }

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

    public String getOrigenId() {
        return origenId;
    }

    public void setOrigenId(String origenId) {
        this.origenId = origenId;
    }

    public String getDestinoId() {
        return destinoId;
    }

    public void setDestinoId(String destinoId) {
        this.destinoId = destinoId;
    }

    public String getComments() {
        return comments;
    }

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

    public TaxiController getTaxiController() {
        return taxiController;
    }

    public void setTaxiController(TaxiController taxiController) {
        this.taxiController = taxiController;
    }

}
