/*
 * 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.MutualAddController;
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.MutualAddType;
import com.arrebol.taxiservicios.model.mutual.MutualAdd;
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 oscarvargas
 */
@Named
@ViewScoped
public class MutualAddBean 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;
            }
            getAddMutualAdd().setId(UUID.randomUUID().toString());
            if (getTipo().equals("SINIESTRO")) {
                getAddMutualAdd().setType(MutualAddType.SINIESTRO);
            } else if (getTipo().equals("CUOTA_MUTUAL")) {
                getAddMutualAdd().setType(MutualAddType.CUOTA_MUTUAL);
            } else if (getTipo().equals("PAGO_LAMINADO")) {
                getAddMutualAdd().setType(MutualAddType.PAGO_LAMINADO);
            } else if (getTipo().equals("PAGO_DEDUCIBLE")) {
                getAddMutualAdd().setType(MutualAddType.PAGO_DEDUCIBLE);
            } else if (getTipo().equals("NUEVO_INGRESO")) {
                getAddMutualAdd().setType(MutualAddType.NUEVO_INGRESO);
            } else if (getTipo().equals("OTROS_INGRESOS")) {
                getAddMutualAdd().setType(MutualAddType.OTROS_INGRESOS);
            }
            
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            getAddMutualAdd().setCreatedOn(calendar.getTime());
            getAddMutualAdd().setLocation(getLoggedUser().getLocation());

            boolean success = getController().addMutualAdd(getAddMutualAdd(), getLoggedUser().getId(), driverId, taxiId);

            if (success) {

                getMutualAdd().clear();
                setMutualAdd(getController().fillDataTableBetweenDates(startDate, endDate, getLoggedUser().getLocation()));
                getAddMutualAdd().setId("");
                getAddMutualAdd().setDescription("");
                getAddMutualAdd().setPayment(0.0);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Ingresos Mutual",
                        "Se agrego correctamente");
            } else {
                logger.error("Sanction " + getAddMutualAdd() + " 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(getSelectedMutualAdd().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 " + getSelectedMutualAdd().getType().getType() + " del día";
                String descBitacora = "Se eliminó la " + getSelectedMutualAdd().getType().getType() + " del chofer " + getSelectedMutualAdd().getDriver().getFirstName()
                        + " " + getSelectedMutualAdd().getDriver().getSecondName()
                        + " " + getSelectedMutualAdd().getDriver().getLastName()
                        + " " + getSelectedMutualAdd().getDriver().getMiddleName()
                        + ", monto " + currencyFormatNumber(getSelectedMutualAdd().getPayment())
                        + " y fecha " + getSelectedMutualAdd().getCreatedOn();

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


                getMutualAdd().remove(getSelectedMutualAdd());

                setSelectedMutualAdd(null);
                setCommentsBitacora("");

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

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

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

    public MutualAddController getController() {
        return controller;
    }

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

    public List<MutualAdd> getMutualAdd() {
        return mutualAdd;
    }

    public void setMutualAdd(List<MutualAdd> mutualAdd) {
        this.mutualAdd = mutualAdd;
    }

    public MutualAdd getSelectedMutualAdd() {
        return selectedMutualAdd;
    }

    public void setSelectedMutualAdd(MutualAdd selectedMutualAdd) {
        this.selectedMutualAdd = selectedMutualAdd;
    }

    public MutualAdd getAddMutualAdd() {
        return addMutualAdd;
    }

    public void setAddMutualAdd(MutualAdd addMutualAdd) {
        this.addMutualAdd = addMutualAdd;
    }

    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 List<Taxi> getTaxis() {
        return getController().fillTaxisComboBox();
    }

    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 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 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 MutualAdd");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setAddMutualAdd(new MutualAdd());
            setController(new MutualAddController());
            setGenericController(new GenericValidationController());
            mutualAdd = getController().fillDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
            setBitacoraController(new BitacoraController());
            setLastStableSmallBox(getGenericController().lastMutualStableSmallBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existMutualStableSmallBoxByCurdate(getLoggedUser()));
        } catch (Exception e) {
            logger.error("init MutualAdd", 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 {
                mutualAdd = 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(MutualAddBean.class);

    private MutualAddController controller;
    private GenericValidationController genericController;
    private List<MutualAdd> mutualAdd;
    private String driverId;
    private String taxiId;
    private MutualAdd selectedMutualAdd;
    private MutualAdd addMutualAdd;
    private String tipo;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private Date startDate;
    private Date endDate;
    private Date lastStableSmallBox;
    private boolean hayCuadre;

}
