/*
 * 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.apc.web.beans.admin;

import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.admin.StatsEmployeeSavingController;
import com.arrebol.apc.controller.util.DateWrapper;
import com.arrebol.apc.model.admin.EmployeeSaving;
import com.arrebol.apc.model.core.HumanResource;
import com.arrebol.apc.model.core.User;
import com.arrebol.apc.model.enums.EmployeeSavingType;
import com.arrebol.apc.model.views.StatsEmployeeSavingView;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author David Rodriguez
 */
@Named("statsEmployeeSavingManager")
@ViewScoped
public class StatsEmployeeSavingBean extends GenericBean implements Serializable, Datatable {

    public void searchHistoricalAction() {
        try {
            if (getStarDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setEmployeeSaving(fillDatatableEmployeeSaving());
                setTotalEmployeeSaving(fillTotalEmployeeSaving());
            }
        } catch (Exception e) {
        }
    }

    public BigDecimal searchTotalEmployeeSavingAction() {
        try {
            if (getStarDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setTotalEmployeeSaving(fillTotalEmployeeSaving());
            }
        } catch (Exception e) {
        }
        return getTotalEmployeeSaving();
    }

    public List<StatsEmployeeSavingView> getDetails(String idUser) {
        try {
            setEmployeeSavingDetails(getEmployeeSavingCtrl().getEmployeeSavingById(getStarDate(), getEndDate(), idUser));
        } catch (Exception e) {
        }
        return null == employeeSavingsDetails ? new ArrayList<>() : employeeSavingsDetails;
    }

    public StatsEmployeeSavingController getEmployeeSavingCtrl() {
        return employeeSavingCtrl;
    }

    public void setEmployeeSavingCtrl(StatsEmployeeSavingController employeeSavingCtrl) {
        this.employeeSavingCtrl = employeeSavingCtrl;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

    public void setGenericCtrl(GenericController genericCtrl) {
        this.genericCtrl = genericCtrl;
    }

    public List<StatsEmployeeSavingView> fillDatatableEmployeeSaving() {
        return getEmployeeSavingCtrl().fillEmployeeSavingDataTable(getStarDate(), getEndDate());
    }

    public BigDecimal fillTotalEmployeeSaving() {
        return getEmployeeSavingCtrl().fillTotalEmployeeSaving(getStarDate(), getEndDate());
    }

    public List<StatsEmployeeSavingView> getEmployeeSaving() {
        return employeeSavings;
    }

    public void setEmployeeSaving(List<StatsEmployeeSavingView> employeeSaving) {
        this.employeeSavings = employeeSaving;
    }

    public List<StatsEmployeeSavingView> getEmployeeSavingDetails() {
        return employeeSavingsDetails;
    }

    public void setEmployeeSavingDetails(List<StatsEmployeeSavingView> employeeSavingsDetails) {
        this.employeeSavingsDetails = employeeSavingsDetails;
    }

    public StatsEmployeeSavingView getSelectedEmployeeSaving() {
        return selectedEmployeeSaving;
    }

    public void setSelectedEmployeeSaving(StatsEmployeeSavingView selectedEmployeeSaving) {
        this.selectedEmployeeSaving = selectedEmployeeSaving;
    }

    public BigDecimal getTotalEmployeeSaving() {
        return totalEmployeeSaving;
    }

    public void setTotalEmployeeSaving(BigDecimal totalEmployeeSaving) {
        this.totalEmployeeSaving = totalEmployeeSaving;
    }
    
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
    
    public BigDecimal getDisposal() {
        return disposal;
    }

    public void setDisposal(BigDecimal disposal) {
        this.disposal = disposal;
    }

    public List<User> getUsers() {
        return genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());
    }

    public String getUserSelectedId() {
        return userSelectedId;
    }

    public void setUserSelectedId(String userSelectedId) {
        this.userSelectedId = userSelectedId;
    }
    
    private StatsEmployeeSavingController employeeSavingCtrl;
    private GenericController genericCtrl;
    private List<StatsEmployeeSavingView> employeeSavings;
    private List<StatsEmployeeSavingView> employeeSavingsDetails;
    private StatsEmployeeSavingView selectedEmployeeSaving;
    private BigDecimal totalEmployeeSaving;
    private String userId;
    private BigDecimal disposal;
    private List<User> users;
    private String userSelectedId;    
        
    public void createEmployeeSaving() {
        User userPayRoll = employeeSavingCtrl.getUserById(userSelectedId);
        
        getDetails(userPayRoll.getHumanResource().getId());
        
         if(disposal.compareTo(BigDecimal.ZERO)==0){
            
            showMessage(FacesMessage.SEVERITY_WARN, "Disposición Incorrecta", "No se puede disponer de 0");
            return;
        
        }
        
        if(disposal.compareTo(BigDecimal.ZERO)<0){
            
            showMessage(FacesMessage.SEVERITY_WARN, "Disposición Incorrecta", "No se puede disponer de un numero negativo");
            return;
        
        }
        
       if (genericCtrl.existStableGeneralBoxByCreatedOn(new Date())) {
           showMessage(FacesMessage.SEVERITY_WARN, "Día cerrado", "No se pueden hacer mas disposiciones de ahorro porque ya se existe un cuadre de caja general de hoy.");
            return;
        }
        
        BigDecimal totalEmployeeSavingDetail = BigDecimal.ZERO;
        for (StatsEmployeeSavingView employeeSaving : employeeSavingsDetails) {
            if (employeeSaving.getType().equals(EmployeeSavingType.SAVING)) {
                totalEmployeeSavingDetail = totalEmployeeSavingDetail.add(employeeSaving.getEmployeeSaving());
            }else{
                totalEmployeeSavingDetail = totalEmployeeSavingDetail.subtract(employeeSaving.getEmployeeSaving());
            }
        }
        
        if(disposal.compareTo(totalEmployeeSavingDetail)<=0){
        EmployeeSaving employeeSaving = new EmployeeSaving();
        employeeSaving.setIdUser(userPayRoll.getHumanResource().getId());
        employeeSaving.setEmployeeSaving(disposal);
        employeeSaving.setCreatedOn(new Date());
        employeeSaving.setCreatedBy(getLoggedUser().getId());
        employeeSaving.setType(EmployeeSavingType.DISPOSAL);

        employeeSavingCtrl.saveEmployeeSaving(employeeSaving);
        showMessage(FacesMessage.SEVERITY_INFO, "Disposición de ahorro", "Se guardó correctamente");
        setEmployeeSaving(fillDatatableEmployeeSaving());
        setTotalEmployeeSaving(fillTotalEmployeeSaving());
        }
        
        else{
            showMessage(FacesMessage.SEVERITY_INFO, "Disposición de ahorro fallida", "No se puede disponer más efectivo del ahorro de esta persona");
        }
        
    }

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        
        Calendar cal = Calendar.getInstance();
       
        cal.set(Calendar.DAY_OF_YEAR, 1);    
        Date start = cal.getTime();
        
        setStarDate(start);
        setEndDate(DateWrapper.getTodayMXTime());

        employeeSavingCtrl = new StatsEmployeeSavingController();
        genericCtrl = new GenericController();
        employeeSavings = fillDatatableEmployeeSaving();
        totalEmployeeSaving = fillTotalEmployeeSaving();
        users = getUsers();
        
        disposal = BigDecimal.ZERO;
    }

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

    @Override
    public void deleteRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
