/*
 * 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.ChangeOwnerController;
import com.arrebol.apc.model.loan.Loan;
import com.arrebol.apc.model.views.AvailablesOwnersView;
import com.arrebol.apc.model.views.CurrentCustomerByLoanView;
import com.arrebol.apc.web.beans.GenericBean;
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.model.DualListModel;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named()
@ViewScoped
public class ChangeOwnerBean extends GenericBean implements Serializable {

    /**
     *
     */
    public void onCurrentOwnerChange() {
        logger.debug("onCurrentOwnerChange");
        try {
            setNewOwners(getController().findAllNewOwners(getLoggedUser().getOffice().getId(), getCurrentOwner()));

            setLoansByCurrentOwner(
                    new DualListModel<>(
                            getController().findAllLoansByCurrentOwner(getLoggedUser().getOffice().getId(), getCurrentOwner()),
                            new ArrayList<>()
                    )
            );

            AvailablesOwnersView owner = getCurrentOwners()
                    .stream()
                    .filter(value -> getCurrentOwner().equals(value.getUserId()))
                    .findAny()
                    .orElse(null);

            setCurrentOwnerFullName(null == owner ? "Error" : owner.getFullName());

            setNewOwner(null);
            setNewOwnerFullName("");
        } catch (Exception e) {
            logger.error("onCurrentOwnerChange", e);

            setNewOwner(null);
            setNewOwnerFullName("");
            setNewOwners(new ArrayList<>());
            setLoansByCurrentOwner(new DualListModel<>(new ArrayList<>(), new ArrayList<>()));
            setCurrentOwners(new ArrayList<>());
        }
    }

    /**
     *
     */
    public void onNewOwnerChange() {
        logger.debug("onNewOwnerChange");
        try {
            setLoansByCurrentOwner(
                    new DualListModel<>(
                            getController().findAllLoansByCurrentOwner(getLoggedUser().getOffice().getId(), getCurrentOwner()),
                            new ArrayList<>()
                    )
            );

            AvailablesOwnersView owner = getNewOwners()
                    .stream()
                    .filter(value -> getNewOwner().equals(value.getUserId()))
                    .findAny()
                    .orElse(null);

            setNewOwnerFullName(null == owner ? "Error" : owner.getFullName());
        } catch (Exception e) {
            logger.error("onNewOwnerChange", e);

            setNewOwners(new ArrayList<>());
            setLoansByCurrentOwner(new DualListModel<>(new ArrayList<>(), new ArrayList<>()));
        }
    }

    /**
     *
     */
    public void changeLoansBetweenUsers() {
        logger.debug("changeLoansBetweenUsers");

        try {
            FacesMessage.Severity severity = FacesMessage.SEVERITY_WARN;
            String messafeFormat = getBundlePropertyFile().getString("message.format.failure");
            String messageTitle = getBundlePropertyFile().getString("change.owner.upper");
            String messageAction = getBundlePropertyFile().getString("updated");

            List<Loan> loans = new ArrayList<>();

            getLoansByCurrentOwner().getTarget().forEach((loanView) -> {
                loans.add(new Loan(loanView.getLoanId()));
            });

            if (getController().changeLoansBetweenUsers(getNewOwner(), loans)) {
                setCurrentOwner(null);
                setCurrentOwnerFullName("");
                setCurrentOwners(getController().findAllCurrentOwners(getLoggedUser().getOffice().getId()));
                setNewOwner(null);
                setNewOwnerFullName("");
                setNewOwners(new ArrayList<>());
                setLoansByCurrentOwner(new DualListModel<>(new ArrayList<>(), new ArrayList<>()));
                
                severity = FacesMessage.SEVERITY_INFO;
                messafeFormat = getBundlePropertyFile().getString("message.format.sucess");
            }

            Object[] param = {messageTitle, messageAction};

            buildAndSendMessage(param, messafeFormat, severity, messageTitle);
        } catch (Exception e) {
            logger.error("changeLoansBetweenUsers", e);
            Object[] param = {getBundlePropertyFile().getString("change.owner.upper")};

            buildAndSendMessage(
                    param,
                    getBundlePropertyFile().getString("message.format.fatal"),
                    FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("change.owner")
            );
        }
    }

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

            setController(new ChangeOwnerController());
            setCurrentOwners(getController().findAllCurrentOwners(getLoggedUser().getOffice().getId()));

            setLoansByCurrentOwner(
                    new DualListModel<>(
                            new ArrayList<>(),
                            new ArrayList<>()
                    )
            );
        } catch (Exception e) {
            logger.error("init", e);
        }
    }

    private static final long serialVersionUID = -7947550003483328090L;
    final Logger logger = LogManager.getLogger(getClass().getName());

    private ChangeOwnerController controller;
    private List<AvailablesOwnersView> currentOwners;
    private List<AvailablesOwnersView> newOwners;
    private DualListModel<CurrentCustomerByLoanView> loansByCurrentOwner;

    private String currentOwner;
    private String newOwner;
    private String currentOwnerFullName;
    private String newOwnerFullName;

    public ChangeOwnerController getController() {
        return controller;
    }

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

    public List<AvailablesOwnersView> getCurrentOwners() {
        return currentOwners;
    }

    public void setCurrentOwners(List<AvailablesOwnersView> currentOwners) {
        this.currentOwners = currentOwners;
    }

    public List<AvailablesOwnersView> getNewOwners() {
        return newOwners;
    }

    public void setNewOwners(List<AvailablesOwnersView> newOwners) {
        this.newOwners = newOwners;
    }

    public DualListModel<CurrentCustomerByLoanView> getLoansByCurrentOwner() {
        return loansByCurrentOwner;
    }

    public void setLoansByCurrentOwner(DualListModel<CurrentCustomerByLoanView> loansByCurrentOwner) {
        this.loansByCurrentOwner = loansByCurrentOwner;
    }

    public String getCurrentOwner() {
        return currentOwner;
    }

    public void setCurrentOwner(String currentOwner) {
        this.currentOwner = currentOwner;
    }

    public String getNewOwner() {
        return newOwner;
    }

    public void setNewOwner(String newOwner) {
        this.newOwner = newOwner;
    }

    public String getCurrentOwnerFullName() {
        return currentOwnerFullName;
    }

    public void setCurrentOwnerFullName(String currentOwnerFullName) {
        this.currentOwnerFullName = currentOwnerFullName;
    }

    public String getNewOwnerFullName() {
        return newOwnerFullName;
    }

    public void setNewOwnerFullName(String newOwnerFullName) {
        this.newOwnerFullName = newOwnerFullName;
    }

}
