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

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.EmployeeController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.SanctionController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.admin.EmployeeSanction;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.enums.EmployeeSanctionType;
import com.arrebol.taxiservicios.model.enums.PersonType;
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("employeeFinantialBean")
@ViewScoped
public class EmployeeFinantialBean extends GenericPersonBean implements Serializable {

    
    public List<EmployeeSanction> getDetails(String id) {
        logger.info("getDetails");
        try {
            setEmployeeSanction(getSanctionController().fillEmployeeSanctionDatatableByEmployeeFinancing(id));

            logger.info("fillEmployeeSanctionDatatableByEmployeeFinancing loaded size " + employeeSanction != null ? employeeSanction.size() : 0);
        } catch (Exception e) {
            logger.error("getDetails", e);
        }
        return null == employeeSanction ? new ArrayList<>() : employeeSanction;
    }
    
    public List<EmployeeSanction> getDetailsSaving(String id) {
        logger.info("getDetails");
        try {
            setEmployeeSanction(getSanctionController().fillEmployeeSanctionDatatableByEmployeeSaving(id));

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

    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 (idEmployee != null && !idEmployee.isEmpty()) {
            Person personTemp = getEmployeeController().getPersonById(idEmployee);

            EmployeeSanction expense = new EmployeeSanction();
            expense.setId(UUID.randomUUID().toString());
            expense.setPayment(getAddSanction().getPayment());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            expense.setCreatedOn(calendar.getTime());
            expense.setDescription(getAddSanction().getDescription());
            expense.setType(EmployeeSanctionType.ABONO_DEUDA);
            expense.setPaymentWeek(0D);
            expense.setAmountToPay(0D);
            expense.setLocation(getLoggedUser().getLocation());

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

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

            personTemp.setAdeudo((float)((personTemp.getAdeudo() == null ? 0F : personTemp.getAdeudo()) - getAddSanction().getPayment()));
            getEmployeeController().editAdeudo(personTemp.getId(), personTemp.getAdeudo(), getLoggedUser());

            setAddSanction(new EmployeeSanction());
        }
    }
    
    public void addSavingDriver() {
        if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden generar más ahorro porque ya existe un cuadre de caja general del día");
                return;
            }
        if (idEmployee != null && !idEmployee.isEmpty()) {
            Person personTemp = getEmployeeController().getPersonById(idEmployee);

            EmployeeSanction expense = new EmployeeSanction();
            expense.setId(UUID.randomUUID().toString());
            expense.setPayment(getAddSanction().getPayment());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            expense.setCreatedOn(calendar.getTime());
            expense.setDescription(getAddSanction().getDescription());
            expense.setType(EmployeeSanctionType.SAVING);
            expense.setPaymentWeek(0D);
            expense.setAmountToPay(0D);
            expense.setLocation(getLoggedUser().getLocation());

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

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

            personTemp.setSaving((double)((personTemp.getSaving()) + getAddSanction().getPayment()));
            getEmployeeController().editSaving(personTemp.getId(), personTemp.getSaving(), getLoggedUser());

            setAddSanction(new EmployeeSanction());
        }
    }
    
    public void addDisposicionDriver() {
        if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden generar más disposición de ahorro porque ya existe un cuadre de caja general del día");
                return;
            }
        if (idEmployee != null && !idEmployee.isEmpty()) {
            Person personTemp = getEmployeeController().getPersonById(idEmployee);

            EmployeeSanction expense = new EmployeeSanction();
            expense.setId(UUID.randomUUID().toString());
            expense.setPayment(getAddSanction().getPayment());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            expense.setCreatedOn(calendar.getTime());
            expense.setDescription(getAddSanction().getDescription());
            expense.setType(EmployeeSanctionType.DISPOSICION_AHORRO);
            expense.setPaymentWeek(0D);
            expense.setAmountToPay(0D);
            expense.setLocation(getLoggedUser().getLocation());

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

            if (success) {
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Disposición de ahorro",
                        "Se agregó correctamente");
            }

            personTemp.setSaving((double)((personTemp.getSaving()) - getAddSanction().getPayment()));
            getEmployeeController().editSaving(personTemp.getId(), personTemp.getSaving(), getLoggedUser());

            setAddSanction(new EmployeeSanction());
        }
    }
    
    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 (idEmployee != null && !idEmployee.isEmpty()) {
            Person personTemp = getEmployeeController().getPersonById(idEmployee);

            EmployeeSanction expense = new EmployeeSanction();
            expense.setId(UUID.randomUUID().toString());
            expense.setPayment(getAddSanction().getPayment());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            expense.setCreatedOn(calendar.getTime());
            expense.setDescription(getAddSanction().getDescription());
            expense.setType(EmployeeSanctionType.AGREGAR_DEUDA);
            expense.setPaymentWeek(getAddSanction().getPaymentWeek());
            expense.setLocation(getLoggedUser().getLocation());
            
            double meses = (expense.getPayment() / getAddSanction().getPaymentWeek())/4;
            double interes = (expense.getPayment() * 0.05) * meses;
            
            expense.setAmountToPay(expense.getPayment() + interes);

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

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

            personTemp.setAdeudo((float)((personTemp.getAdeudo() == null ? 0F : personTemp.getAdeudo()) + expense.getAmountToPay()));
            getEmployeeController().editAdeudo(personTemp.getId(), personTemp.getAdeudo(), getLoggedUser());
            
            setAddSanction(new EmployeeSanction());

        }
    }

    public void fillSanctionFeeDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                employeeSanctionDetail = getSanctionController().fillEmployeeSanctionDatatableByEmployeeFinancing(getStartDate(), getEndDate(), getLoggedUser().getLocation());
                
                totalAbono = 0D;
                totalDeuda = 0D;

                if(getEmployeeSanctionDetail()!= null && !getEmployeeSanctionDetail().isEmpty())
                {
                    for(EmployeeSanction tmp : getEmployeeSanctionDetail())
                    {
                        if(tmp.getType() == EmployeeSanctionType.ABONO_DEUDA)
                            totalAbono = totalAbono + tmp.getPayment();
                        
                        if(tmp.getType() == EmployeeSanctionType.ABONO_DEUDA_NOMINA)
                            totalAbono = totalAbono + tmp.getPayment();

                        if(tmp.getType() == EmployeeSanctionType.AGREGAR_DEUDA)
                            totalDeuda = totalDeuda + tmp.getPayment();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @PostConstruct
    public void init() {
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setEmployeeController(new EmployeeController());
            setSanctionController(new SanctionController());
            setGenericController(new GenericValidationController());
            setBitacoraController(new BitacoraController());
            setEmployee(getEmployeeController().findListOfPersonsByType(PersonType.EMPLOYEE, getLoggedUser().getLocation().getId()));
            setEmployeeSanctionDetail(getSanctionController().fillEmployeeSanctionDatatableByEmployeeFinancing(getStartDate(), getEndDate(), getLoggedUser().getLocation()));
            totalFinancing = 0F;
            totalSaving = 0D;
            totalAbono = 0D;
            totalDeuda = 0D;
            setAddSanction(new EmployeeSanction());
            if(getEmployee()!= null && !getEmployee().isEmpty())
            {
                for(PersonListView person : getEmployee())
                {
                    if(person.getAdeudoByCustomer() != null)
                    {
                        totalFinancing += person.getAdeudoByCustomer();
                        totalSaving += person.getSaving();
                    }
                        
                        
                }
            }
            
            if(getEmployeeSanctionDetail()!= null && !getEmployeeSanctionDetail().isEmpty())
                {
                    for(EmployeeSanction tmp : getEmployeeSanctionDetail())
                    {
                        if(tmp.getType() == EmployeeSanctionType.ABONO_DEUDA)
                            totalAbono = totalAbono + tmp.getPayment();

                        if(tmp.getType() == EmployeeSanctionType.AGREGAR_DEUDA)
                            totalDeuda = totalDeuda + tmp.getPayment();
                    }
                }
        } catch (Exception e) {
            logger.error("Finantial employee init", e);
        }
    }

    private static final long serialVersionUID = -7284027390656669184L;

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

    private EmployeeController employeeController;
    private SanctionController sanctionController;
    private GenericValidationController genericController;

    private List<PersonListView> employee;
    private List<EmployeeSanction> employeeSanction;
    private List<EmployeeSanction> employeeSanctionDetail;
    private EmployeeSanction selectedEmployeeSanction;
    private PersonListView selectedEmployee;
    private EmployeeSanction addSanction;
    private float totalFinancing;
    private String idEmployee;
    private String tipo;
    private double totalSaving;
    private Date startDate;
    private Date endDate;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private Date lastStableSmallBox;
    private boolean hayCuadre;
    private double totalDeuda;
    private double totalAbono;
    
    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 EmployeeSanction getSelectedEmployeeSanction() {
        return selectedEmployeeSanction;
    }

    public void setSelectedEmployeeSanction(EmployeeSanction selectedEmployeeSanction) {
        this.selectedEmployeeSanction = selectedEmployeeSanction;
    }

    public List<EmployeeSanction> getEmployeeSanctionDetail() {
        return employeeSanctionDetail;
    }

    public void setEmployeeSanctionDetail(List<EmployeeSanction> employeeSanctionDetail) {
        this.employeeSanctionDetail = employeeSanctionDetail;
    }

    public double getTotalDeuda() {
        return totalDeuda;
    }

    public void setTotalDeuda(double totalDeuda) {
        this.totalDeuda = totalDeuda;
    }

    public double getTotalAbono() {
        return totalAbono;
    }

    public void setTotalAbono(double totalAbono) {
        this.totalAbono = totalAbono;
    }

    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 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 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 GenericValidationController getGenericController() {
        return genericController;
    }

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

    public String getTipo() {
        return tipo;
    }

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

    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 List<PersonListView> getEmployee() {
        return employee;
    }

    public void setEmployee(List<PersonListView> employee) {
        this.employee = employee;
    }

    public EmployeeController getEmployeeController() {
        return employeeController;
    }

    public void setEmployeeController(EmployeeController employeeController) {
        this.employeeController = employeeController;
    }

    public PersonListView getSelectedEmployee() {
        return selectedEmployee;
    }

    public void setSelectedEmployee(PersonListView selectedEmployee) {
        this.selectedEmployee = selectedEmployee;
    }

    public EmployeeSanction getAddSanction() {
        return addSanction;
    }

    public void setAddSanction(EmployeeSanction addSanction) {
        this.addSanction = addSanction;
    }

    public String getIdEmployee() {
        return idEmployee;
    }

    public void setIdEmployee(String idEmployee) {
        this.idEmployee = idEmployee;
    }

    public List<EmployeeSanction> getEmployeeSanction() {
        return employeeSanction;
    }

    public void setEmployeeSanction(List<EmployeeSanction> employeeSanction) {
        this.employeeSanction = employeeSanction;
    }

    public double getTotalSaving() {
        return totalSaving;
    }

    public void setTotalSaving(double totalSaving) {
        this.totalSaving = totalSaving;
    }
    
}
