/*
 * 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.mutual;

import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.BitacoraController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.mutual.MutualOutController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.enums.MutualOutType;
import com.arrebol.taxiservicios.model.mutual.MutualOut;
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.el.ELException;
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 oscarvargas
 */
@Named
@ViewScoped
public class MutualOutBean extends TaxiGenericBean implements Serializable, Datatable {

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

    @Override
    public void addRow() {
        logger.info("add Mutual Add");
        try {

            if(getGenericController().existMutualStableSmallBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden eliminar más registros porque ya existe un cuadre de caja chica en mutual del día");
                return;
            }

            if (getGenericController().existMutualClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            getAddMutualOut().setId(UUID.randomUUID().toString());
            if (getTipo().equals("PAGO_LAMINADO")) {
                getAddMutualOut().setType(MutualOutType.PAGO_LAMINADO);
            } else if (getTipo().equals("PAGO_DEDUCIBLE")) {
                getAddMutualOut().setType(MutualOutType.PAGO_DEDUCIBLE);
            } else if (getTipo().equals("COMPRAS")) {
                getAddMutualOut().setType(MutualOutType.COMPRAS);
            } else if (getTipo().equals("GASOLINA")) {
                getAddMutualOut().setType(MutualOutType.GASOLINA);
            } else if (getTipo().equals("NOMINA")) {
                getAddMutualOut().setType(MutualOutType.NOMINA);
            } else if (getTipo().equals("DISPOSICION")) {
                getAddMutualOut().setType(MutualOutType.DISPOSICION);
            } else if (getTipo().equals("OTROS_EGRESOS")) {
                getAddMutualOut().setType(MutualOutType.OTROS_EGRESOS);
            } else if (getTipo().equals("RENTA_VEHICULO")) {
                getAddMutualOut().setType(MutualOutType.RENTA_VEHICULO);
            }
            
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            getAddMutualOut().setCreatedOn(calendar.getTime());
            getAddMutualOut().setLocation(getLoggedUser().getLocation());

            boolean success = getController().addMutualOut(getAddMutualOut(), getLoggedUser().getId(), driverId, taxiId);

            if (success) {

                getMutualOut().clear();
                setMutualOut(getController().fillDataTableBetweenDates(startDate, endDate, getLoggedUser().getLocation()));
                getAddMutualOut().setId("");
                getAddMutualOut().setDescription("");
                getAddMutualOut().setPayment(0.0);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Ingresos Mutual",
                        "Se agrego correctamente");
            } else {
                logger.error("Sanction " + getAddMutualOut() + " was not saved");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Ingresos Mutual",
                        "No se pudo guardar el registro");
            }
        } catch (Exception e) {
            logger.error("addSanction: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    "Ingresos Mutual",
                    "Ocurrió un error al guardar el registro");
        }
    }

    @Override
    public void deleteRow() {
        logger.info("deleteRow in MutualAdd");
        try {
            
            if(getGenericController().existMutualStableSmallBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden eliminar más registros porque ya existe un cuadre de caja chica en mutual del día");
                return;
            }

            if (getGenericController().existMutualClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            boolean success = getController().deleteById(getSelectedMutualOut().getId());

            if (success) {

                if (null == getCommentsBitacora() || getCommentsBitacora().trim().equals("")) {
                    setCommentsBitacora("El usuario " + getLoggedUser().getUserName() + " no agrego comentarios a la hora de borrar este registro");
                }

                String actionBitacora = "Eliminar " + getSelectedMutualOut().getType().getType() + " del día";
                String descBitacora = "Se eliminó la " + getSelectedMutualOut().getType().getType() + " del chofer " + getSelectedMutualOut().getDriver().getFirstName()
                        + " " + getSelectedMutualOut().getDriver().getSecondName()
                        + " " + getSelectedMutualOut().getDriver().getLastName()
                        + " " + getSelectedMutualOut().getDriver().getMiddleName()
                        + ", monto " + currencyFormatNumber(getSelectedMutualOut().getPayment())
                        + " y fecha " + getSelectedMutualOut().getCreatedOn();

                getBitacoraController().saveNewRecordInBitacora(createNewRecordInBitacora(UUID.randomUUID().toString(), actionBitacora, getCommentsBitacora(), descBitacora),
                        getLoggedUser().getLocation().getId());


                getMutualOut().remove(getSelectedMutualOut());

                setSelectedMutualOut(null);
                setCommentsBitacora("");

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Egresos Mutual",
                        "Se eliminó el egresos de Mutual");
            } else {
                logger.error("MutualAdd " + getSelectedMutualOut() + "was not deleted");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Egresos Mutual",
                        "Ocurrió un error al intentar eliminar el registro");
            }

        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    "Egresos Mutual",
                    getBundlePropertyFile().getString("sanction.delete.exception.desc"));
        }
    }

    public MutualOutController getController() {
        return controller;
    }

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

    public List<MutualOut> getMutualOut() {
        return mutualOut;
    }

    public void setMutualOut(List<MutualOut> mutualOut) {
        this.mutualOut = mutualOut;
    }

    public MutualOut getSelectedMutualOut() {
        return selectedMutualOut;
    }

    public void setSelectedMutualOut(MutualOut selectedMutualOut) {
        this.selectedMutualOut = selectedMutualOut;
    }

    public MutualOut getAddMutualOut() {
        return addMutualOut;
    }

    public void setAddMutualOut(MutualOut addMutualOut) {
        this.addMutualOut = addMutualOut;
    }

    public String getDriverId() {
        return driverId;
    }

    public void setDriverId(String driverId) {
        this.driverId = driverId;
    }

    public String getTipo() {
        return tipo;
    }

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

    public List<Person> getDrivers() {
        return getController().fillDriversComboBox();
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public BitacoraController getBitacoraController() {
        return bitacoraController;
    }

    public void setBitacoraController(BitacoraController bitacoraController) {
        this.bitacoraController = bitacoraController;
    }

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

    public void setCommentsBitacora(String commentsBitacora) {
        this.commentsBitacora = commentsBitacora;
    }
    
    public List<Taxi> getTaxis() {
        return getController().fillTaxisComboBox();
    }

    public Date getStartDate() {
        if(startDate == null)
        {
            return new Date();
        }
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        if(endDate == null)
        {
            return new Date();
        }
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getLastStableSmallBox() {
        return lastStableSmallBox;
    }

    public void setLastStableSmallBox(Date lastStableSmallBox) {
        this.lastStableSmallBox = lastStableSmallBox;
    }

    public boolean isHayCuadre() {
        return hayCuadre;
    }

    public void setHayCuadre(boolean hayCuadre) {
        this.hayCuadre = hayCuadre;
    }

    @PostConstruct
    public void init() {
        logger.info("init MutualOut");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setAddMutualOut(new MutualOut());
            setController(new MutualOutController());
            setGenericController(new GenericValidationController());
            mutualOut = getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
            setBitacoraController(new BitacoraController());
            setLastStableSmallBox(getGenericController().lastMutualStableSmallBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existMutualStableSmallBoxByCurdate(getLoggedUser()));
        } catch (ELException ele) {
            logger.error("init MutualOut", ele);
        } catch (Exception e) {
            logger.error("init MutualOut", e);
        }
    }
    
    public void fillDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                mutualOut = getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
            }
        } catch (Exception e) {
            logger.error("", 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 String getTaxiId() {
        return taxiId;
    }

    public void setTaxiId(String taxiId) {
        this.taxiId = taxiId;
    }
    
    private static final long serialVersionUID = -4506036879677260356L;

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

    private MutualOutController controller;
    private GenericValidationController genericController;
    private List<MutualOut> mutualOut;
    private String driverId;
    private String taxiId;
    private MutualOut selectedMutualOut;
    private MutualOut addMutualOut;
    private String tipo;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private Date startDate;
    private Date endDate;
    private Date lastStableSmallBox;
    private boolean hayCuadre;

}
