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

import com.arrebol.taxiservicios.beans.admin.*;
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.ExpenseCompanyController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.mutual.MutualIniciosController;
import com.arrebol.taxiservicios.model.admin.ExpenseCompany;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseCompanyType;
import com.arrebol.taxiservicios.model.mutual.MutualInicios;
import java.io.Serializable;
import java.math.BigDecimal;
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 Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named("mutualIniciosBean")
@ViewScoped
public class MutualIniciosBean extends TaxiGenericBean implements Serializable, Datatable {

    /**
     *
     */
    public void updateExpenseCompanyList() {
        logger.info("updateExpenseCompanyList");
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("payment.in"),
                        getBundlePropertyFile().getString("start.date.after.error"));
            } else {
                setUpDates(false);
                setExpenseCompanies(
                        getController().findExpenseCompanyByTypeAndBetweenDates(
                                ExpenseCompanyType.PAYMENT_IN,
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId())
                );
            }
        } catch (Exception e) {
            logger.error("updateExpenseCompanyList", e);
        }
    }

    @Override
    public void addRow() {
        logger.info("addRow");
        if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden generar más entradas porque ya existe un cuadre de caja general del día");
                return;
            }
        try {
            MutualInicios ec = new MutualInicios(
                    UUID.randomUUID().toString(),
                    getAmount(),
                    getReason(),
                    new User(userId, true),
                    BasicType.ENEBLED,
                    new User(getLoggedUser().getId(), ""),
                    new Date(),
                    getLoggedUser().getLocation());

            if (getController().saveExpenseCompany(ec)) {
                setUpDates(false);
                setExpenseCompanies(
                        getController().findExpenseCompanyByTypeAndBetweenDates(
                                ExpenseCompanyType.PAYMENT_IN,
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId())
                );

                setAmount(null);
                setReason(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("payment.in"),
                        getBundlePropertyFile().getString("payment.in.add.success.desc"));
            } else {
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("payment.in"),
                        getBundlePropertyFile().getString("payment.in.add.exception.desc"));
            }
        } catch (Exception e) {
            logger.error("addRow", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("payment.in"),
                    getBundlePropertyFile().getString("payment.in.add.exception.desc"));
        }
    }

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

            if (getController().updateExpenseCompanyStatus(getExpenseCompanyToUpdate().getId(), BasicType.DISABLED, new User(getLoggedUser().getId(), ""))) {
                if (null == getCommentsBitacora() || getCommentsBitacora().trim().equals("")) {
                    setCommentsBitacora("El usuario " + getLoggedUser().getUserName() + " no agrego comentarios a la hora de borrar esta entrada");
                }

                String actionBitacora = "Eliminar entradas";
                String descBitacora = "Se eliminó la entrada con monto "
                        + currencyFormatNumber(getExpenseCompanyToUpdate().getAmount()) + " y fecha " + getExpenseCompanyToUpdate().getCreatedOn();

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

                setExpenseCompanyToUpdate(null);
                setCommentsBitacora("");
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("payment.in"),
                        getBundlePropertyFile().getString("payment.in.delete.success.desc"));
            } else {
                showMessage(FacesMessage.SEVERITY_FATAL,
                        getBundlePropertyFile().getString("payment.in"),
                        getBundlePropertyFile().getString("payment.in.delete.exception.desc"));
            }
        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("payment.in"),
                    getBundlePropertyFile().getString("payment.in.delete.exception.desc"));
        }
    }

    @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.
    }

    /**
     * Setup start date and end date.
     *
     * @param init True if comes from @PostConstruct otherwise false.
     */
    private void setUpDates(boolean init) {
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();

        if (!init) {
            startCalendar.setTime(getStartDate());
            endCalendar.setTime(getEndDate());
        } else {
            startCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            endCalendar.setTime(new Date());
        }

        startCalendar.add(Calendar.HOUR_OF_DAY, 0);
        startCalendar.add(Calendar.MINUTE, 0);
        startCalendar.add(Calendar.SECOND, 0);
        startCalendar.add(Calendar.MILLISECOND, 0);

        endCalendar.add(Calendar.HOUR_OF_DAY, 22);
        endCalendar.add(Calendar.MINUTE, 59);
        endCalendar.add(Calendar.SECOND, 59);
        endCalendar.add(Calendar.MILLISECOND, 0);

        setStartDate(startCalendar.getTime());
        setEndDate(endCalendar.getTime());
    }

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();

            setUpDates(true);
            setController(new MutualIniciosController());
            setBitacoraController(new BitacoraController());
            setGenericController(new GenericValidationController());
            setUsersInicio(getController().findAllSystemUserByLocation(getLoggedUser().getLocation()));
            setLastStableGeneralBox(getGenericController().lastStableGeneralBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()));
            setExpenseCompanies(
                    getController().findExpenseCompanyByTypeAndBetweenDates(
                            ExpenseCompanyType.PAYMENT_IN,
                            getStartDate(),
                            getEndDate(),
                            getLoggedUser().getLocation().getId())
            );
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private GenericValidationController genericController;
    private Date lastStableGeneralBox;
    private boolean hayCuadre;
    private MutualIniciosController controller;
    private List<MutualInicios> expenseCompanies;
    private MutualInicios expenseCompanyToUpdate;
    private MutualInicios newExpenseCompany;
    private Date startDate;
    private Date endDate;
    private BigDecimal amount;
    private String reason;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private String userId;
    private List<User> usersInicio;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public List<User> getUsersInicio() {
        return usersInicio;
    }

    public void setUsersInicio(List<User> usersInicio) {
        this.usersInicio = usersInicio;
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public Date getLastStableGeneralBox() {
        return lastStableGeneralBox;
    }

    public void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }

    public boolean isHayCuadre() {
        return hayCuadre;
    }

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

    public MutualIniciosController getController() {
        return controller;
    }

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

    public List<MutualInicios> getExpenseCompanies() {
        return expenseCompanies;
    }

    public void setExpenseCompanies(List<MutualInicios> expenseCompanies) {
        this.expenseCompanies = expenseCompanies;
    }

    public MutualInicios getExpenseCompanyToUpdate() {
        return expenseCompanyToUpdate;
    }

    public void setExpenseCompanyToUpdate(MutualInicios expenseCompanyToUpdate) {
        this.expenseCompanyToUpdate = expenseCompanyToUpdate;
    }

    public MutualInicios getNewExpenseCompany() {
        return newExpenseCompany;
    }

    public void setNewExpenseCompany(MutualInicios newExpenseCompany) {
        this.newExpenseCompany = newExpenseCompany;
    }

    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 BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    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;
    }

    private static final long serialVersionUID = 3399229987467371585L;
    final Logger logger = LogManager.getLogger(MutualIniciosBean.class);
}
