package com.fp.frontend.controller.pgeneral.gene;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.primefaces.event.SelectEvent;

import com.fp.dto.AbstractDataTransport;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pgeneral.lov.BranchLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneBranch;
import com.fp.persistence.pgeneral.gene.TgeneCanton;
import com.fp.persistence.pgeneral.gene.TgeneCity;
import com.fp.persistence.pgeneral.gene.TgeneCountry;
import com.fp.persistence.pgeneral.gene.TgeneProvince;

/**
 * Clase controladora del bean TgeneMenu.
 *
 * @author WPA
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class OfficeAndBranchController extends AbstractController<AbstractDataTransport> {

    private static final long serialVersionUID = 1L;

    public OfficeAndBranchController() throws Exception {
        super(AbstractDataTransport.class);
    }

    @ManagedProperty(value = "#{branchController}")
    private BranchController branch;

    @ManagedProperty(value = "#{officeController}")
    private OfficeController office;

    /**
     * Atributo para la lista de objetos TgeneCountry
     */
    private List<TgeneCountry> lCountry;

    /**
     * Atributo para la lista de objetos TgeneProvince
     */
    private List<TgeneProvince> lProvince;

    /**
     * Atributo para la lista de objetos TgeneCanton
     */
    private List<TgeneCanton> lCanton;

    /**
     * Atributo para la lista de objetos TgeneCity
     */
    private List<TgeneCity> lCity;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //Listas
        this.lCountry = CountryController.find();
        this.lProvince = new ArrayList<TgeneProvince>();
        this.lCanton = new ArrayList<TgeneCanton>();
        this.lCity = new ArrayList<TgeneCity>();
    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {
            this.recperpage = 4; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "TGENEMENU";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    protected void querydatabase() {

        try {
            this.branch.query();

            if (this.office.getMfilters().get("") != null && !this.office.getMfilters().get("pk.branchcode").equals("")) {
                this.office.query();
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void save() {
        try {
            Request request = this.callerhelper.getRequest();
            //Dto General
            //DtoSave dtosave = super.getDtoSave();

            //Dto Sucursal
            DtoSave dtosavebranch = this.branch.getDtoSave();

            //Dto Oficina
            DtoSave dtosaveoffice = this.office.getDtoSave();

            if (!dtosavebranch.pendingProcess() && !dtosaveoffice.pendingProcess()) {
                return;
            }

            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();

            if (dtosavebranch.pendingProcess()) {
                msave.put(this.branch.getBeanalias(), dtosavebranch);
            }
            if (dtosaveoffice.pendingProcess()) {
                msave.put(this.office.getBeanalias(), dtosaveoffice);
            }

            request.setSaveTables(msave);
            Response resp = this.callerhelper.executeSave(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                //this.postCommit(resp);
                this.branch.postCommit(resp);
                this.office.postCommit(resp);
                MessageHelper.setMessageInfo(resp);
            } else {
                MessageHelper.setMessageError(resp);
            }

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Llama al Lov MenuLevel
     */
    public void openBranchLov() {
        Map<String, List<String>> params = new HashMap<>();
        BranchLovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del Lov MenuLevel para transacciones por nivel
     *
     * @param event
     * @throws Exception
     */
    public void onReturnBranchLov(SelectEvent event) throws Exception {
        TgeneBranch t = (TgeneBranch) event.getObject();
        this.office.initRecPage();
        this.office.addFilter("pk.branchcode", t.getPk().getBranchcode().toString());
        this.office.getMfilelds().put("branchdesc", t.getDescription());
        this.office.query();
    }

    public void onChangeCountry() {
        if (this.office.getRecord().getCountrycode() != null) {
            this.lProvince = ProvinceController.find(this.office.getRecord().getCountrycode());
            this.lCanton = new ArrayList<TgeneCanton>();
            this.lCity = new ArrayList<TgeneCity>();
        }
    }

    public void onChangeProvince() {
        if (this.office.getRecord().getProvincecode() != null) {
            this.lCanton = CantonController.find(this.office.getRecord().getCountrycode(), this.office.getRecord().getProvincecode());
            this.lCity = new ArrayList<TgeneCity>();
        }
    }

    public void onChangeCanton() {
        if (this.office.getRecord().getCantoncode() != null) {
            this.lCity = CityController.find(this.office.getRecord().getCountrycode(), this.office.getRecord().getProvincecode(), this.office.getRecord().getCantoncode());
        }
    }

    /**
     * Consulta las listas al abrir el editar
     */
    public void openEdit() {
        if (this.office.getRecord() != null) {
            this.lProvince = ProvinceController.find(this.office.getRecord().getCountrycode());
            this.lCanton = CantonController.find(this.office.getRecord().getCountrycode(), this.office.getRecord().getProvincecode());
            this.lCity = CityController.find(this.office.getRecord().getCountrycode(), this.office.getRecord().getProvincecode(), this.office.getRecord().getCantoncode());
        }
    }

    /**
     * Entrega el valor de OfficeController
     *
     * @return office
     */
    public OfficeController getOffice() {
        return office;
    }

    /**
     * Fija el valor de OfficeController
     *
     * @param office
     */
    public void setOffice(OfficeController office) {
        this.office = office;
    }

    /**
     * Entrega el valor de BranchController
     *
     * @return branch
     */
    public BranchController getBranch() {
        return branch;
    }

    /**
     * fija el valor de BranchController
     *
     * @param branch
     */
    public void setBranch(BranchController branch) {
        this.branch = branch;
    }

    /**
     * Entrega el valor de lCountry
     *
     * @return lCountry
     */
    public List<TgeneCountry> getlCountry() {
        return lCountry;
    }

    /**
     * Fija el valor de lCountry
     *
     * @param lCountry
     */
    public void setlCountry(List<TgeneCountry> lCountry) {
        this.lCountry = lCountry;
    }

    /**
     * Entrega el valor de lProvince
     *
     * @return lProvince
     */
    public List<TgeneProvince> getlProvince() {
        return lProvince;
    }

    /**
     * Fija el valor de lProvince
     *
     * @param lProvince
     */
    public void setlProvince(List<TgeneProvince> lProvince) {
        this.lProvince = lProvince;
    }

    /**
     * Entrega el valor de lCanton
     *
     * @return lCanton
     */
    public List<TgeneCanton> getlCanton() {
        return lCanton;
    }

    /**
     * Fija el valor de lCanton
     *
     * @param lCanton
     */
    public void setlCanton(List<TgeneCanton> lCanton) {
        this.lCanton = lCanton;
    }

    /**
     * Entrega el valor de lCity
     *
     * @return lCity
     */
    public List<TgeneCity> getlCity() {
        return lCity;
    }

    /**
     * Fija el valor de lCity
     *
     * @param lCity
     */
    public void setlCity(List<TgeneCity> lCity) {
        this.lCity = lCity;
    }

}
