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

import com.arrebol.apc.controller.admin.AdministrationPersonSearchViewController;
import com.arrebol.apc.controller.admin.EndorsementController;
import com.arrebol.apc.model.catalog.People;
import com.arrebol.apc.model.enums.ActiveStatus;
import com.arrebol.apc.model.enums.PeopleType;
import com.arrebol.apc.model.views.AdministrationPersonSerchView;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
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 Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named("endorsementManager")
@ViewScoped
public class EndorsementBean extends GenericPersonSearchBean implements Serializable {

    public List<AdministrationPersonSerchView> autoCompleteSearchByName(String nameToSearch) {
        List<AdministrationPersonSerchView> results;
        try {
            results = executeAutoComplete(nameToSearch, PeopleType.ENDORSEMENT);
        } catch (Exception e) {
            results = new ArrayList<>();

            logger.error("autoCompleteSearchByName", e);
        }
        return results;
    }

    public void searchPersonAction() {
        try {
            if ((null == getSearchPersonName() || "".equals(getSearchPersonName().trim())) && getRouteId().equals("All")) {
                showMessage(FacesMessage.SEVERITY_WARN, "Ingresar nombre de persona a buscar", "Para hacer una busqueda general en las rutas debes propocionar el nombre de la persona a buscar-");
            } else {
                if (getRouteId().equals("All")) {
                    executeQueryLike(true, PeopleType.ENDORSEMENT);
                } else if (null != getSearchPersonName() && !"".equals(getSearchPersonName().trim())) {
                    boolean allRoutes = false;

                    if (getRouteId().equals("All")) {
                        allRoutes = true;
                    }

                    executeQueryLike(allRoutes, PeopleType.ENDORSEMENT);
                } else if (null == getSearchPersonName() || "".equals(getSearchPersonName().trim())) {
                    fillPersonList(PeopleType.ENDORSEMENT);
                }
            }
        } catch (Exception e) {
            logger.error("searchPersonAction", e);
            setPersonList(new ArrayList<>());
        }
    }

    public List<People> fillDatatableEndorsement() {
        return endorsementCtrl.fillEndorsementsDatatable(getLoggedUser().getOffice().getId());
    }

    @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) {
        showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1));
    }

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

    @Override
    public void deleteRow() {
        getEndorsementCtrl().updatePeopleByStatus(ActiveStatus.DISABLED, getSelectedPerson().getId(), getLoggedUser().getUser().getId());
        cleaningView();

        showMessage(FacesMessage.SEVERITY_INFO, "Aval Eliminado", "Se eliminó correctamente.");
    }

    public void updatePeopleTypeById() {
        if (selectedEndorsement.getPeopleType().equals(PeopleType.BOTH)) {
            showMessage(FacesMessage.SEVERITY_INFO, "Advertencia", "El aval ya se encuentra como cliente.");
            return;
        }
        //endorsementCtrl.updatePeopleTypeById(PeopleType.BOTH, selectedEndorsement.getId(), getLoggedUser().getUser().getId());
        //endorsement = null;
        //endorsement = fillDatatableEndorsement();
        //selectedEndorsement = null;

        getEndorsementCtrl().updatePeopleTypeById(PeopleType.BOTH, getSelectedPerson().getId(), getLoggedUser().getUser().getId());
        cleaningView();

        showMessage(FacesMessage.SEVERITY_INFO, "Aval modificado", "Se modificó correctamente.");
    }

    private void cleaningView() {
        getPersonList().remove(getSelectedPerson());
        setSelectedPerson(null);
    }

    final Logger logger = LogManager.getLogger(getClass());

    private EndorsementController endorsementCtrl;
    private List<People> endorsement;
    private People selectedEndorsement;

    @PostConstruct
    public void init() {
        try {
            loadBundlePropertyFile();

            endorsementCtrl = new EndorsementController();
            setAdminSearchController(new AdministrationPersonSearchViewController());

            setRoutes(getAdminSearchController().findAllActiveRoutesByOfficce(getLoggedUser().getOffice().getId()));
        } catch (Exception e) {
        }
    }

    /**
     *
     * @param outcome
     * @return
     */
    public String detailEndorsement(String outcome) {
        return outcome;
    }

    public EndorsementController getEndorsementCtrl() {
        return endorsementCtrl;
    }

    public void setEndorsementCtrl(EndorsementController endorsementCtrl) {
        this.endorsementCtrl = endorsementCtrl;
    }

    public List<People> getEndorsement() {
        return endorsement;
    }

    public void setEndorsement(List<People> endorsement) {
        this.endorsement = endorsement;
    }

    public People getSelectedEndorsement() {
        return selectedEndorsement;
    }

    public void setSelectedEndorsement(People selectedEndorsement) {
        this.selectedEndorsement = selectedEndorsement;
    }
}
