/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.taxiservicios.beans.admin.driver;

import com.arrebol.taxiservicios.beans.admin.client.*;
import com.arrebol.taxiservicios.beans.GenericPersonBean;
import com.arrebol.taxiservicios.controller.admin.BitacoraController;
import com.arrebol.taxiservicios.controller.admin.CustomerController;
import com.arrebol.taxiservicios.controller.admin.DriverController;
import com.arrebol.taxiservicios.controller.admin.ExpenseController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.SanctionController;
import com.arrebol.taxiservicios.controller.sp.report.ReportCustomerPayController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.admin.Expense;
import com.arrebol.taxiservicios.model.admin.FinancingDriver;
import com.arrebol.taxiservicios.model.admin.Sanction;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseStatusType;
import com.arrebol.taxiservicios.model.enums.ExpenseType;
import com.arrebol.taxiservicios.model.enums.PersonType;
import com.arrebol.taxiservicios.model.enums.SanctionType;
import com.arrebol.taxiservicios.model.view.PersonListFinancingView;
import com.arrebol.taxiservicios.model.view.PersonListView;
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;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named("driverFinantialBean")
@ViewScoped
public class DriverFinantialBean extends GenericPersonBean implements Serializable {

    /**
     *
     * @param outcome
     * @return
     */
    public String editCustomer(String outcome) {
        return outcome;
    }
    
    public List<Sanction> getDetails(String id) {
        logger.info("getDetails");
        try {
            setSanction(getSanctionController().fillSanctionDatatableByDriverFinancing(id));

            logger.info("fillSanctionDatatableByDriverFinancing loaded size " + sanction != null ? sanction.size() : 0);
        } catch (Exception e) {
            logger.error("getDetails", e);
        }
        return null == sanction ? new ArrayList<>() : sanction;
    }

    public void addFinantialDriver() {
        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 pueden agregar más registros porque ya existe un cuadre de caja chica del día");
                return;
            }
        if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden agregar más registros porque ya existe un cuadre de caja general del día");
                return;
            }
        if (idChofer != null && !idChofer.isEmpty()) {
            Person personTemp = getDriverController().getPersonById(idChofer);
            getFinancing().setActiveStatus(BasicType.ENEBLED);
            getFinancing().setActuallyDebit(personTemp.getAdeudo() - getFinancing().getPayment());
            getFinancing().setCreatedBy(getLoggedUser());
            getFinancing().setCreatedOn(new Date());
            getFinancing().setDiscount(0D);
            getFinancing().setLastDebit(personTemp.getAdeudo());
            getFinancing().setMonthDebit(personTemp.getAdeudo());
            getFinancing().setDriver(personTemp);
            getFinancing().setIncrease(0D);
            getFinancing().setId(UUID.randomUUID().toString());
            getFinancing().setActive(Boolean.TRUE);

           // if (getDriverController().saveFinancingDriver(getFinancing())) {
                Sanction expense = new Sanction();
                expense.setId(UUID.randomUUID().toString());
                expense.setPayment(getFinancing().getPayment());
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.HOUR, -6);
                expense.setCreatedOn(calendar.getTime());
                expense.setDescription(getFinancing().getComments());
                expense.setPaymentDate(calendar.getTime());
                expense.setType(SanctionType.ABONO_DEUDA);
                expense.setLocation(getLoggedUser().getLocation());
                expense.setStatus(ExpenseStatusType.AUTHORIZED);

                boolean success = getSanctionController().addSanction(
                        expense,
                        getLoggedUser().getId(),
                        (null != idChofer && !"".equals(idChofer.trim())) ? idChofer : null);

                if (success) {
                    showMessage(FacesMessage.SEVERITY_INFO,
                            "Abono al adeudo",
                            "Se agregó correctamente");
                }

                personTemp.setAdeudo((float) getFinancing().getActuallyDebit());
                getDriverController().editBlackListDriver(personTemp.getId(), "", personTemp.getAdeudo(), getLoggedUser());
           // }

            setFinancing(new FinancingDriver());
        }
    }
    
    public void addAdeudoDriver() {
        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 pueden agregar más registros porque ya existe un cuadre de caja chica del día");
                return;
            }
        if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden agregar más registros porque ya existe un cuadre de caja general del día");
                return;
            }
        if (idChofer != null && !idChofer.isEmpty()) {
            Person personTemp = getDriverController().getPersonById(idChofer);
            getFinancing().setActiveStatus(BasicType.ENEBLED);
            getFinancing().setActuallyDebit(personTemp.getAdeudo() + getFinancing().getPayment());
            getFinancing().setCreatedBy(getLoggedUser());
            getFinancing().setCreatedOn(new Date());
            getFinancing().setDiscount(0D);
            getFinancing().setLastDebit(personTemp.getAdeudo());
            getFinancing().setMonthDebit(personTemp.getAdeudo());
            getFinancing().setDriver(personTemp);
            getFinancing().setIncrease(0D);
            getFinancing().setId(UUID.randomUUID().toString());
            getFinancing().setActive(Boolean.TRUE);

           // if (getDriverController().saveFinancingDriver(getFinancing())) {
                Sanction expense = new Sanction();
                expense.setId(UUID.randomUUID().toString());
                expense.setPayment(getFinancing().getPayment());
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.HOUR, -6);
                expense.setCreatedOn(calendar.getTime());
                expense.setDescription(getFinancing().getComments());
                expense.setPaymentDate(calendar.getTime());
                expense.setType(SanctionType.AGREGAR_DEUDA);
                expense.setLocation(getLoggedUser().getLocation());
                expense.setStatus(ExpenseStatusType.AUTHORIZED);

                boolean success = getSanctionController().addSanction(
                        expense,
                        getLoggedUser().getId(),
                        (null != idChofer && !"".equals(idChofer.trim())) ? idChofer : null);

                if (success) {
                    showMessage(FacesMessage.SEVERITY_INFO,
                            "Se agrega adeudo",
                            "Se agregó correctamente");
                }

                personTemp.setAdeudo((float) getFinancing().getActuallyDebit());
                getDriverController().editBlackListDriver(personTemp.getId(), "", personTemp.getAdeudo(), getLoggedUser());
           // }

            setFinancing(new FinancingDriver());
        }
    }
    
    public String seeDetails(String outcome) {
        return outcome;
    }
    
    public void fillSanctionFeeDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                sanctionDriver = getSanctionController().fillSanctionDatatableFinancing(getStartDate(), getEndDate(), getLoggedUser().getLocation());
                
                totalDriverAbono = 0D;
                totalDriverDeuda = 0D;

                if(getSanctionDriver() != null && !getSanctionDriver().isEmpty())
                {
                    for(Sanction tmp : getSanctionDriver())
                    {
                        if(tmp.getType() == SanctionType.ABONO_DEUDA)
                            totalDriverAbono = totalDriverAbono + tmp.getPayment();

                        if(tmp.getType() == SanctionType.AGREGAR_DEUDA)
                            totalDriverDeuda = totalDriverDeuda + tmp.getPayment();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    
    public void deleteRow() {
        logger.info("deleteRow in Sanction");
        try {
            
            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 (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 pueden eliminar más registros porque ya existe un cuadre de caja chica del día");
                return;
            }
            
            Sanction tmpSanction = getSanctionController().getSanctionById(getSelectedSanction().getId());
            boolean success = getSanctionController().deleteSanctionById(getSelectedSanction().getId());

            if (success) {
                
                if (tmpSanction.getType() == SanctionType.AGREGAR_DEUDA) {
                    Person tmp = getDriverController().getPersonById(tmpSanction.getDriver().getId());
                    float adeudo = tmp.getAdeudo() - Float.valueOf(tmpSanction.getPayment().toString());
                    getDriverController().editBlackListDriver(tmp.getId(), "", adeudo, getLoggedUser());
                }
                
                if (tmpSanction.getType() == SanctionType.ABONO_DEUDA) {
                    Person tmp = getDriverController().getPersonById(tmpSanction.getDriver().getId());
                    float adeudo = tmp.getAdeudo() + Float.valueOf(tmpSanction.getPayment().toString());
                    getDriverController().editBlackListDriver(tmp.getId(), "", adeudo, getLoggedUser());
                }

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

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

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

              
                getSanctionDriver().remove(getSelectedSanction());
                

                setSelectedSanction(null);
                setCommentsBitacora("");

                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("sanction.delete.title"),
                        getBundlePropertyFile().getString("sanction.delete.success.desc"));
            } else {
                logger.error("Sanction " + getSelectedSanction() + "was not deleted");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("sanction.delete.title"),
                        getBundlePropertyFile().getString("sanction.delete.fail.desc"));
            }

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

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

    @PostConstruct
    public void init() {
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setFinancing(new FinancingDriver());
            setController(new DriverController());
            setBitacoraController(new BitacoraController());
            setCustomerController(new CustomerController());
            setGenericController(new GenericValidationController());
            setDriverController(new DriverController());
            setSanctionController(new SanctionController());
            setLastStableSmallBox(getGenericController().lastStableSmallBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableSmallBoxByCurdate(getLoggedUser()));
            setDriver(getController().findListOfPersonsByTypeFinancing(PersonType.DRIVER, getLoggedUser().getLocation()));
            setSanctionDriver(getSanctionController().fillSanctionDatatableFinancing(getStartDate(), getEndDate(), getLoggedUser().getLocation()));
            totalFinancing = 0F;
            totalDriverAbono = 0D;
            totalDriverDeuda = 0D;
            
            if(getSanctionDriver() != null && !getSanctionDriver().isEmpty())
            {
                for(Sanction tmp : getSanctionDriver())
                {
                    if(tmp.getType() == SanctionType.ABONO_DEUDA)
                        totalDriverAbono = totalDriverAbono + tmp.getPayment();
                    
                    if(tmp.getType() == SanctionType.AGREGAR_DEUDA)
                        totalDriverDeuda = totalDriverDeuda + tmp.getPayment();
                }
            }
            if(getDriver()!= null && !getDriver().isEmpty())
            {
                for(PersonListFinancingView person : getDriver())
                {
                    if(person.getAdeudoByCustomer() != null)
                        totalFinancing += person.getAdeudoByCustomer();
                }
            }
        } catch (Exception e) {
            logger.error("Finantial customer init", e);
        }
    }

    private static final long serialVersionUID = -7284027390656669184L;

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

    private CustomerController customerController;
    private DriverController driverController;
    private ReportCustomerPayController reportController;
    private SanctionController sanctionController;
    private GenericValidationController genericController;

    private List<PersonListFinancingView> driver;
    private List<Sanction> sanction;
    private List<Sanction> sanctionDriver;
    private Sanction selectedSanction;
    private PersonListFinancingView selectedDriver;
    private FinancingDriver financing;
    private float totalFinancing;
    private double totalDriverDeuda;
    private double totalDriverAbono;
    private String idChofer;
    private Date startDate;
    private Date endDate;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private Date lastStableSmallBox;
    private boolean hayCuadre;
    
    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 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;
    }

    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 double getTotalDriverDeuda() {
        return totalDriverDeuda;
    }

    public void setTotalDriverDeuda(double totalDriverDeuda) {
        this.totalDriverDeuda = totalDriverDeuda;
    }

    public double getTotalDriverAbono() {
        return totalDriverAbono;
    }

    public void setTotalDriverAbono(double totalDriverAbono) {
        this.totalDriverAbono = totalDriverAbono;
    }

    public Sanction getSelectedSanction() {
        return selectedSanction;
    }

    public void setSelectedSanction(Sanction selectedSanction) {
        this.selectedSanction = selectedSanction;
    }

    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<Sanction> getSanctionDriver() {
        return sanctionDriver;
    }

    public void setSanctionDriver(List<Sanction> sanctionDriver) {
        this.sanctionDriver = sanctionDriver;
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public List<Sanction> getSanction() {
        return sanction;
    }

    public void setSanction(List<Sanction> sanction) {
        this.sanction = sanction;
    }

    public String getIdChofer() {
        return idChofer;
    }

    public void setIdChofer(String idChofer) {
        this.idChofer = idChofer;
    }

    public DriverController getDriverController() {
        return driverController;
    }

    public void setDriverController(DriverController driverController) {
        this.driverController = driverController;
    }

    public float getTotalFinancing() {
        return totalFinancing;
    }

    public void setTotalFinancing(float totalFinancing) {
        this.totalFinancing = totalFinancing;
    }

    public SanctionController getSanctionController() {
        return sanctionController;
    }

    public void setSanctionController(SanctionController sanctionController) {
        this.sanctionController = sanctionController;
    }
    
    public ReportCustomerPayController getReportController() {
        return reportController;
    }

    public void setReportController(ReportCustomerPayController reportController) {
        this.reportController = reportController;
    }

    public List<Person> getChoferCombo() {
        return getDriverController().getAllPersonsByPersonTye2(PersonType.DRIVER);
    }

    public FinancingDriver getFinancing() {
        return financing;
    }

    public void setFinancing(FinancingDriver financing) {
        this.financing = financing;
    }

    public CustomerController getCustomerController() {
        return customerController;
    }

    public void setCustomerController(CustomerController customerController) {
        this.customerController = customerController;
    }

    public List<PersonListFinancingView> getDriver() {
        return driver;
    }

    public void setDriver(List<PersonListFinancingView> driver) {
        this.driver = driver;
    }

    public PersonListFinancingView getSelectedDriver() {
        return selectedDriver;
    }

    public void setSelectedDriver(PersonListFinancingView selectedDriver) {
        this.selectedDriver = selectedDriver;
    }


}
