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

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.DriverController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.SanctionController;
import com.arrebol.taxiservicios.controller.catalog.BankCardController;
import com.arrebol.taxiservicios.controller.catalog.BankCardKardexController;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.model.admin.Sanction;
import com.arrebol.taxiservicios.model.catalog.BankCard;
import com.arrebol.taxiservicios.model.catalog.BankCardKardex;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.enums.BankCardKardexType;
import com.arrebol.taxiservicios.model.enums.ExpenseStatusType;
import com.arrebol.taxiservicios.model.enums.SanctionType;
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("managerSanction")
@ViewScoped
public class ManagerSanction 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.
    }
    
    public void autorizar() {
        logger.info("noPrintSale");

        try {
            boolean success = getController().autorizar(getSelectedSanction().getId());

            if (success) {
                setSelectedSanction(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Autorizar",
                        "Se autorizó correctamente");
                fillSanctionDataTableBetweenDates();
            } else {
                logger.error("Sale " + getSelectedSanction() + "was not changed to no print");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Autorizar",
                        "No se pudo autorizar");
            }

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

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("sale.noprint.title"),
                    getBundlePropertyFile().getString("sale.noprint.exception.desc"));
        }

    }
    
    public void autorizarPending() {
        logger.info("autorizarPending");

        try {
            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 puede hacer ninguna acción porque ya existe un cuadre de caja chica del día");
                return;
            }
            boolean success = getController().autorizarDeposit(getSelectedSanction().getId());

            if (success) {
                
                BankCardKardex bankCardKardexObj = new BankCardKardex();

                bankCardKardexObj.setBankCard(getSelectedSanction().getBankCard());
                bankCardKardexObj.setAmount(getSelectedSanction().getPayment());
                bankCardKardexObj.setAmountBefore(getSelectedSanction().getBankCard().getBalance());
                bankCardKardexObj.setAmountAfter(bankCardKardexObj.getAmountBefore()+bankCardKardexObj.getAmount());
                bankCardKardexObj.setKardexType(BankCardKardexType.INCOME);
                bankCardKardexObj.setDescription("Pago de multa");
                bankCardKardexObj.setLocation(getSelectedSanction().getLocation());
                
                BankCardKardexController bankCardKardexCtrl = new BankCardKardexController(); 
                bankCardKardexCtrl.save(bankCardKardexObj, getLoggedUser().getId());

                BankCard bankCard = getSelectedSanction().getBankCard();
                
                bankCard.setBalance(bankCardKardexObj.getAmountAfter());
                
                BankCardController bankCardCtrl = new BankCardController();
                
                bankCardCtrl.save(bankCard, getLoggedUser().getId());
                
                setSelectedSanction(null);

                showMessage(FacesMessage.SEVERITY_INFO,
                        "Autorizar",
                        "Se autorizó correctamente");
                fillSanctionDataTablePending();
            } else {
                logger.error("Sale " + getSelectedSanction() + "was not changed to no print");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Autorizar",
                        "No se pudo autorizar");
            }

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

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("sale.noprint.title"),
                    getBundlePropertyFile().getString("sale.noprint.exception.desc"));
        }

    }


    @Override
    public void addRow() {
        logger.info("add Sanction");
        try {

            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().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().existStableSmallBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se pueden guardar más registros porque ya existe un cuadre de caja chica del día");
                return;
            }
            getAddSanction().setId(UUID.randomUUID().toString());
            if (getTipo().equals("SANCTION")) {
                getAddSanction().setType(SanctionType.SANCTION);
            } else if (getTipo().equals("DISPOSITION")) {
                getAddSanction().setType(SanctionType.DISPOSITION);
            } else if (getTipo().equals("ACCIDENT")) {
                getAddSanction().setType(SanctionType.ACCIDENT);
            } else if (getTipo().equals("ADD")) {
                getAddSanction().setType(SanctionType.ADD);
            } else if (getTipo().equals("ESTUDIO")) {
                getAddSanction().setType(SanctionType.ESTUDIO);
            } else if (getTipo().equals("RETORNO_EFECTIVO")) {
                getAddSanction().setType(SanctionType.RETORNO_EFECTIVO);
            } else if (getTipo().equals("DISPOSICION_INGRESO")) {
                getAddSanction().setType(SanctionType.DISPOSICION_INGRESO);
            } else if (getTipo().equals("GASTO_SIN_AFECTAR")) {
                getAddSanction().setType(SanctionType.GASTO_SIN_AFECTAR);
            } else if (getTipo().equals("INGRESO_SINIESTRO")) {
                getAddSanction().setType(SanctionType.INGRESO_SINIESTRO);
            } else if (getTipo().equals("ABONO_DEUDA")) {
                getAddSanction().setType(SanctionType.ABONO_DEUDA);
            } else if (getTipo().equals("DISPOSICION_FINIQUITO")) {
                getAddSanction().setType(SanctionType.DISPOSICION_FINIQUITO);
            } else if (getTipo().equals("AGREGAR_DEUDA")) {
                getAddSanction().setType(SanctionType.AGREGAR_DEUDA);
            } else if (getTipo().equals("INGRESO_PAGO_LAMINADO")) {
                getAddSanction().setType(SanctionType.INGRESO_PAGO_LAMINADO);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -6);
            getAddSanction().setCreatedOn(calendar.getTime());
            getAddSanction().setLocation(getLoggedUser().getLocation());
            getAddSanction().setStatus(ExpenseStatusType.AUTHORIZED);
            
            if(isDeposit()){
                getAddSanction().setStatus(ExpenseStatusType.PENDING);
                getAddSanction().setBankCard(new BankCard(getBankCardId()));
            
            }

            boolean success = getController().addSanction(getAddSanction(), getLoggedUser().getId(), driverId);

            if (success) {

                if (getTipo().equals("AGREGAR_DEUDA")) {
                    Person tmp = getDriverController().getPersonById(driverId);
                    float adeudo = tmp.getAdeudo() + Float.valueOf(getAddSanction().getPayment().toString());
                    getDriverController().editBlackListDriver(driverId, "", adeudo, getLoggedUser());
                }
                
                if (getTipo().equals("ABONO_DEUDA")) {
                    Person tmp = getDriverController().getPersonById(driverId);
                    float adeudo = tmp.getAdeudo() - Float.valueOf(getAddSanction().getPayment().toString());
                    getDriverController().editBlackListDriver(driverId, "", adeudo, getLoggedUser());
                }
                sanction.clear();
                sanction = getController().fillSanctionDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
                addSanction.setId("");
                addSanction.setDescription("");
                addSanction.setPayment(0.0);

                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("sanction.add.title"),
                        getBundlePropertyFile().getString("sanction.add.success.desc"));
            } else {
                logger.error("Sanction " + getAddSanction() + " was not saved");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("sanction.add.title"),
                        getBundlePropertyFile().getString("sanction.add.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("addSanction: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("sanction.add.title"),
                    getBundlePropertyFile().getString("sanction.add.exception.desc"));
        }
    }

    @Override
    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 = getController().getSanctionById(getSelectedSanction().getId());
            boolean success = getController().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 gasto administrativo");
                }

                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());

                switch (getSelectedSanction().getType()) {
                    case FEE:
                        getFee().remove(getSelectedSanction());
                        break;
                    default:
                        getSanction().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"));
        }
    }

    public SanctionController getController() {
        return controller;
    }

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

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

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

    public String getDriverId() {
        return driverId;
    }

    public void setDriverId(String driverId) {
        this.driverId = driverId;
    }

    public Sanction getSelectedSanction() {
        return selectedSanction;
    }

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

    public Sanction getAddSanction() {
        return addSanction;
    }

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

    public String getTipo() {
        return tipo;
    }

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

    public List<Person> getDrivers() {
        return getController().fillDriversComboBox();
    }

    public List<Sanction> getFee() {
        return fee;
    }

    public void setFee(List<Sanction> fee) {
        this.fee = fee;
    }

    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 DriverController getDriverController() {
        return driverController;
    }

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

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

    public List<Sanction> getSanctionPending() {
        return sanctionPending;
    }

    public void setSanctionPending(List<Sanction> sanctionPending) {
        this.sanctionPending = sanctionPending;
    }

    public boolean isDeposit() {
        return deposit;
    }

    public void setDeposit(boolean deposit) {
        this.deposit = deposit;
    }

    public String getBankCardId() {
        return bankCardId;
    }

    public void setBankCardId(String bankCardId) {
        this.bankCardId = bankCardId;
    }

    public BankCardController getBankCardController() {
        return bankCardController;
    }

    public void setBankCardController(BankCardController bankCardController) {
        this.bankCardController = bankCardController;
    }

    public List<BankCard> getBankCards() {
        return bankCards;
    }

    public void setBankCards(List<BankCard> bankCards) {
        this.bankCards = bankCards;
    }
    
    

    @PostConstruct
    public void init() {
        logger.info("init sanction");
        try {
            loadBundlePropertyFile();
            initOneWeekBeforeToCurrdate();
            setAddSanction(new Sanction());
            setController(new SanctionController());
            setDriverController(new DriverController());
            setGenericController(new GenericValidationController());
            setBankCardController(new BankCardController());
            sanction = getController().fillSanctionDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
            sanctionPending = getController().fillSanctionDataTablePending(getLoggedUser().getLocation());
            fee = getController().fillSanctionFeeDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
            setBitacoraController(new BitacoraController());
            setLastStableSmallBox(getGenericController().lastStableSmallBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableSmallBoxByCurdate(getLoggedUser()));
            setBankCards(getBankCardController().findAllBankCardsByLocation(getLoggedUser().getLocation().getId()));
            setDeposit(false);
        } catch (Exception e) {
            logger.error("init sanction", e);
        }
    }
    
    public void fillSanctionDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                sanction = getController().fillSanctionDataTableBetweenDates(getStartDate(), getEndDate(), getLoggedUser().getLocation());
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    public void fillSanctionDataTablePending() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                sanctionPending = getController().fillSanctionDataTablePending(getLoggedUser().getLocation());
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    
    public void fillSanctionFeeDataTableBetweenDates() {
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                fee = getController().fillSanctionFeeDataTableBetweenDates(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) {

        }
    }
    
    private static final long serialVersionUID = -4506036879677260356L;

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

    private SanctionController controller;
    private DriverController driverController;
    private GenericValidationController genericController;
    private List<Sanction> sanction;
    private List<Sanction> sanctionPending;
    private String driverId;
    private Sanction selectedSanction;
    private Sanction addSanction;
    private String tipo;
    private List<Sanction> fee;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private Date startDate;
    private Date endDate;
    private Date lastStableSmallBox;
    private boolean hayCuadre;
     private boolean deposit;
    private String bankCardId;
    private BankCardController bankCardController;
    private List<BankCard> bankCards;

}
