package com.fp.frontend.controller.armas.parametros;

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

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

import javax.faces.context.FacesContext;

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.armas.funcionalidad.ArmaExcell;
import com.fp.frontend.controller.armas.funcionalidad.RegistroArmController;
import com.fp.frontend.controller.armas.funcionalidad.TotalArmasController;
import com.fp.frontend.controller.armas.solicitud.SolicitudController;
import com.fp.frontend.controller.armas.solicitud.SolicitudTramiteController;
import com.fp.frontend.controller.pcustomer.PersonDetailController;
import com.fp.frontend.controller.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.controller.pgeneral.gene.CountryController;
import com.fp.frontend.controller.pgeneral.gene.ProvinceController;
import com.fp.frontend.controller.security.LoginController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.parmas.param.TarmTipoArmaExplosivo;
import com.fp.persistence.parmas.soli.TarmArmas;
import com.fp.persistence.parmas.soli.TarmSolicitud;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pgeneral.gene.TgeneCanton;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;
import com.fp.persistence.pgeneral.gene.TgeneCity;
import com.fp.persistence.pgeneral.gene.TgeneCountry;
import com.fp.persistence.pgeneral.gene.TgeneProvince;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;

/**
 * Clase controladora del bean
 *
 * @author Jorge Vaca.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class ImportacionController extends AbstractController<AbstractDataTransport> {

    public ImportacionController() throws Exception {
        super(AbstractDataTransport.class);
        // TODO Auto-generated constructor stub
    }

    private static final long serialVersionUID = 1L;

    @ManagedProperty(value = "#{registroArmController}")
    private RegistroArmController registroArmController;

    @ManagedProperty(value = "#{armaController}")
    private ArmaController armaController;

    /*
    @ManagedProperty(value = "#{armaControllerProduccion}")
    private ArmaControllerProduccion armaControllerProduccion;
     */
    @ManagedProperty(value = "#{totalArmasController}")
    private TotalArmasController totalArmasController;

    private Boolean tiporegistro;

    private Boolean aux;

    private Date fechaactual;
    private List<TgeneCatalogDetail> ltiporegistro;

    private List<TgeneCatalogDetail> laddresstype;

    private List<TgeneProvince> lprovinces;

    private List<TgeneCanton> lcantones;

    private List<TgeneCity> lciudades;

    private List<TgeneCountry> lcountry;

    private TgeneCountry pais;

    private List<TgeneCity> lcities;

    private TgeneCatalogDetail cdetalle;

    private Date fechadesolicitud;

    public void changeType() {
        if (this.registroArmController.getRecord().getTiporegistro() == null) {
            setTiporegistro(false);
        } else if (this.registroArmController.getRecord().getTiporegistro().equals("PRO")) {

            setTiporegistro(false);

        } else {
            setTiporegistro(true);

        }
    }

    public Boolean getAux() {
        return aux;
    }

    public void setAux(Boolean aux) {
        this.aux = aux;
    }

    public TotalArmasController getTotalArmasController() {
        return totalArmasController;
    }

    public void setTotalArmasController(TotalArmasController totalArmasController) {
        this.totalArmasController = totalArmasController;
    }

    //   @ManagedProperty(value = "#{importacionArmasDetalleController}")
//    private ImportacionArmasDetalleController importacionArmasDetalleController;
    @ManagedProperty(value = "#{loginController}")
    private LoginController loginController;

    public RegistroArmController getRegistroArmController() {
        return registroArmController;
    }

    public void setRegistroArmController(
            RegistroArmController RegistroArmController) {
        this.registroArmController = RegistroArmController;
    }

    //Datos quemados de Prueba
    private List<TarmSolicitud> lsolicitud;

    private TarmSolicitud solicitud;
    //Fin de Datos quemados de prueba

    private TcustPersonDetail persondetail;

    //private TarmSolicitud solicitudpersondata;
    private List<TcustPersonDetail> lperson;

    public List<TgeneCatalogDetail> getLaddresstype() {
        return laddresstype;
    }

    public void setLaddresstype(List<TgeneCatalogDetail> laddresstype) {
        this.laddresstype = laddresstype;
    }

    public List<TgeneProvince> getLprovinces() {
        return lprovinces;
    }

    public void setLprovinces(List<TgeneProvince> lprovinces) {
        this.lprovinces = lprovinces;
    }

    public List<TgeneCanton> getLcantones() {
        return lcantones;
    }

    public void setLcantones(List<TgeneCanton> lcantones) {
        this.lcantones = lcantones;
    }

    public List<TgeneCountry> getLcountry() {
        return lcountry;
    }

    public void setLcountry(List<TgeneCountry> lcountry) {
        this.lcountry = lcountry;
    }

    public List<TgeneCity> getLcities() {
        return lcities;
    }

    public void setLcities(List<TgeneCity> lcities) {
        this.lcities = lcities;
    }

    public List<TarmSolicitud> getLsolicitud() {
        return lsolicitud;
    }

    public void setLsolicitud(List<TarmSolicitud> lsolicitud) {
        this.lsolicitud = lsolicitud;
    }

    public TarmSolicitud getSolicitud() {
        return solicitud;
    }

    public void setSolicitud(TarmSolicitud solicitud) {
        this.solicitud = solicitud;
    }

    public List<TcustPersonDetail> getLperson() {
        return lperson;
    }

    public void setLperson(List<TcustPersonDetail> lperson) {
        this.lperson = lperson;
    }

    @PostConstruct
    private void postconstruct() {

        this.init();
        // Inicializa autoconsulta
        super.startQuery();

    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {

            crearRegistro();
            this.lrecord = new ArrayList<>();
            this.beanalias = "IMPORTACION";

            pais = new TgeneCountry();
            aux = false;
            fechaactual = new Date();
            fechadesolicitud = new Date();
            TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("TSAFEUSERDETAIL");
            //solicitud.setPersoncode(tsafeUserDetail.getPk().getPersoncode());
            setPersondetail(PersonDetailController.find(tsafeUserDetail.getPk().getPersoncode().toString()));
            setLtiporegistro(CatalogDetailController.find("TIPOREGISTRO", "REG"));
            armaController.setPersoncode(tsafeUserDetail.getPk().getPersoncode());
            setLaddresstype(CatalogDetailController.find("ADDRESSTYPE"));
            setLcountry(CountryController.find());
            pais = CountryController.findcountry("EC");
            //armaController.setPais(pais.getPk());
            setTiporegistro(false);
            setLprovinces(ProvinceController.find(pais.getPk()));
            cdetalle = CatalogDetailController.findxCodigoCodcatalogo(getPersondetail().getIdentificationcatalog(), getPersondetail().getIdentificationcatalogcode());

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

    @Override
    protected void querydatabase() {

    }

    public void actualizarsolicitudImportacionArmas() throws Exception {
        TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("TSAFEUSERDETAIL");

        registroArmController.getRecord().setFcreacion(new java.sql.Date(new Date().getTime()));

        if (fechadesolicitud != null) {
            registroArmController.getRecord().setFechasolicitud(new java.sql.Date(fechadesolicitud.getTime()));
        }
        registroArmController.getRecord().setPersoncode(tsafeUserDetail.getPk().getPersoncode());
        registroArmController.getRecord().setTiporegistrocodigo("TIPOREGISTRO");
        registroArmController.update();

    }

    public void crearRegistro() throws Exception {
        registroArmController.create();
    }

    public void validarTramite(String tramite) {

        TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("TSAFEUSERDETAIL");
        String solicitud = SolicitudTramiteController.findByNumTramite(tramite).getPk().getCsolicitud();
        aux = SolicitudController.existeRegistroPersona(tsafeUserDetail.getPk().getPersoncode(), solicitud);

    }

    public void actualizarTotales() throws Exception {

        totalArmasController.update();
        for (TarmArmas object : armaController.getLrecord()) {
            TiposArmasExplosivosController.findarma(object.getCtipoarmaexplosivo());
        }
    }
//importacionController.armaController.record.provincecode

    @Override
    public void save() {
        try {
            if (armaController.getLrecord() == null || armaController.getLrecord().isEmpty()) {
                return;
            }
            actualizarsolicitudImportacionArmas();
            Request request = this.callerhelper.getRequest();
            DtoSave dtosave = this.armaController.getDtoSave(true);
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            msave.put(armaController.getBeanalias(), dtosave); // adicionar metadata de mantenimiento para cada tabla.
            dtosave.setPosition(1);

            DtoSave dtosaveSol = this.registroArmController.getDtoSave(true);
            dtosaveSol.setPosition(2);
            msave.put(registroArmController.getBeanalias(), dtosaveSol);

            DtoSave dtosaveTot = this.totalArmasController.getDtoSave(true);
            dtosaveTot.setPosition(3);
            msave.put(totalArmasController.getBeanalias(), dtosaveTot);
            request.setSaveTables(msave);

            Response resp = this.callerhelper.executeSave(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {

                this.armaController.postCommit(resp);
                this.registroArmController.postCommit(resp);
                this.totalArmasController.postCommit(resp);
                this.armaController.clearAll();
                this.registroArmController.clearAll();
                this.totalArmasController.clearAll();
                MessageHelper.setMessageInfo(resp);
            } else {
                MessageHelper.setMessageError(resp);
            }
            //armaController.setSave(false);

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            //armaController.setSave(false);
        } finally {
            try {
                crearRegistro();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    @Override
    public void postCommit(Response response) throws Exception {
        this.armaController.postCommit(response);
        this.registroArmController.postCommit(response);
        this.totalArmasController.postCommit(response);
    }

    public ArmaController getArmaController() {
        return armaController;
    }

    public void setArmaController(ArmaController armaController) {
        this.armaController = armaController;
    }

    public LoginController getLoginController() {
        return loginController;
    }

    public void setLoginController(LoginController loginController) {
        this.loginController = loginController;
    }

    public TcustPersonDetail getPersondetail() {
        return persondetail;
    }

    public void setPersondetail(TcustPersonDetail persondetail) {
        this.persondetail = persondetail;
    }

    public TgeneCatalogDetail getCdetalle() {
        return cdetalle;
    }

    public void setCdetalle(TgeneCatalogDetail cdetalle) {
        this.cdetalle = cdetalle;
    }

    public List<TgeneCity> getLciudades() {
        return lciudades;
    }

    public void setLciudades(List<TgeneCity> lciudades) {
        this.lciudades = lciudades;
    }

    public TgeneCountry getPais() {
        return pais;
    }

    public void setPais(TgeneCountry pais) {
        this.pais = pais;
    }

    public List<TgeneCatalogDetail> getLtiporegistro() {
        return ltiporegistro;
    }

    public void setLtiporegistro(List<TgeneCatalogDetail> ltiporegistro) {
        this.ltiporegistro = ltiporegistro;
    }

    public Boolean getTiporegistro() {
        return tiporegistro;
    }

    public void setTiporegistro(Boolean tiporegistro) {
        this.tiporegistro = tiporegistro;
    }

    public Date getFechadesolicitud() {
        return fechadesolicitud;
    }

    public void setFechadesolicitud(Date fechadesolicitud) {
        this.fechadesolicitud = fechadesolicitud;
    }

    public Date getFechaactual() {
        return fechaactual;
    }

    public void setFechaactual(Date fechaactual) {
        this.fechaactual = fechaactual;
    }

}
