package com.fp.frontend.controller.security;

import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.frontend.controller.alfresco.AlfrescoController;
import com.fp.frontend.controller.armas.parametros.CentroControlArmasController;
import com.fp.frontend.controller.armas.parametros.TarmCentroControlJurController;
import com.fp.frontend.controller.armas.solicitud.DocumentoHabilitanteController;
import com.fp.frontend.controller.armas.solicitud.SolicitudController;
import com.fp.frontend.controller.armas.solicitud.TarmTramiteController;
import com.fp.frontend.controller.armas.solicitud.TramiteArmasController;
import com.fp.frontend.controller.pcustomer.PersonAddressController;
import com.fp.frontend.controller.pcustomer.PersonDetailController;
import com.fp.frontend.controller.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.controller.pgeneral.gene.ParametersController;
import com.fp.frontend.controller.pgeneral.gene.ProvinceController;
import com.fp.frontend.controller.pgeneral.gene.TerminosCondicionesController;
import com.fp.frontend.helper.CallerHelper;
import com.fp.frontend.helper.MessageHelper;
import com.fp.frontend.utility.EnumParametros;
import com.fp.persistence.commondb.exception.CommondbException;
import com.fp.persistence.parmas.param.TarmCentroControl;
import com.fp.persistence.parmas.param.TarmCentroControlJur;
import com.fp.persistence.parmas.param.TarmTramite;
import com.fp.persistence.parmas.soli.TarmDocumentoHabilitante;
import com.fp.persistence.parmas.soli.TarmSolicitud;
import com.fp.persistence.parmas.soli.TarmTerminos;
import com.fp.persistence.pcustomer.gene.TcustPersonAddress;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;
import com.fp.persistence.pgeneral.gene.TgeneParameters;
import com.fp.persistence.pgeneral.gene.TgeneProvince;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;
import com.fp.persistence.pgeneral.safe.TsafeUserProfile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.application.NavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.context.RequestContext;
import org.primefaces.model.StreamedContent;

@ManagedBean
@SessionScoped
public class LoginController {

    private Request request;
    private MaiaMenu maiaMenu;
    private Map<String, Object> mdata = new HashMap();
    private final Map<String, Object> mlocation = new HashMap();
    private List<Map<String, Object>> lcompany;
    private List<TsafeUserProfile> lprofile;
    private String changepassword;
    private boolean renderBpmData = false;
    private String casLogoutUrl;
    private String profilecode;
    private String rutaTerminos;
    private StreamedContent content;
    private boolean alertaInicio = Boolean.FALSE;
    private List<TarmDocumentoHabilitante> ldocumentoscaducarse;

    @PostConstruct
    private void postconstruct() {
        this.request = new Request();
        this.request.setCompany(Integer.valueOf(1));

        HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        this.request.setTerminalCode(httpServletRequest.getRemoteAddr());
        this.request.put("ip", httpServletRequest.getRemoteAddr());
        this.request.put("host", httpServletRequest.getLocalAddr());

        fillCompanies();
        this.maiaMenu = new MaiaMenu();
    }

    public void authenticate() throws Throwable {
        System.out.println("autentificacion debe cambiar : ");
        try {
            System.out.println("changepassword debe cambiar: ");
            String user = this.mdata.get("a").toString();
            String pass = this.mdata.get("b").toString();
            this.request.put("login", user);

            CallerHelper ch = new CallerHelper();
            Response resp = ch.login(this.request, user, pass);
            TarmTerminos terminos = TerminosCondicionesController.findxIdentificacion(user);
            if ((resp.getResponseCode().compareTo("0") == 0) && (terminos == null)) {
                
                System.out.println("terminos");
                try {
                    this.rutaTerminos = ParametersController.find("CODIGO.TERMINOS.COND", "1").getTextvalue();
                    this.content = AlfrescoController.downloadDocument(this.rutaTerminos);
                } catch (Exception e) {
                    System.out.println("error al obtener el parametro CODIGO.TERMINOS.COND");
                }
                RequestContext requestContext = RequestContext.getCurrentInstance();
                requestContext.execute("PF('aceptaTerminosCond').show()");
            } else if (resp.getResponseCode().compareTo("0") == 0) {
                TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) resp.get("TSAFEUSERDETAIL");
                manageloginresponse(tsafeUserDetail);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("TSAFEUSERDETAIL", tsafeUserDetail);
                if (this.changepassword.equalsIgnoreCase("N")) {
                    FacesContext ctx = FacesContext.getCurrentInstance();
                    ExternalContext externalContext = ctx.getExternalContext();
                    NavigationHandler handler = ctx.getApplication().getNavigationHandler();
                    handler.handleNavigation(ctx, null, "workspace");

                    externalContext.redirect(externalContext.getRequestContextPath() + "/" + "pages/workspace.xhtml");

                    this.request.setBrowser(obtainBrowserName((String) externalContext.getRequestHeaderMap().get("User-Agent")));
                    this.request.setOperativesystem(obtainSOName((String) externalContext.getRequestHeaderMap().get("User-Agent")));

                    changeprofile();
                } else {
                    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
                    ec.redirect(ec.getRequestContextPath() + "/" + "change-password.xhtml");
                    System.out.println("debe cambiar la clave : " + ec.getRequestContextPath() + "/" + "passwordExpired.xhtml");
                }
            } else {
                MessageHelper.setMessageError(resp);
            }
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    public void aceptaTerminosCondicion() {
        String user = this.mdata.get("a").toString();
        String pass = this.mdata.get("b").toString();
        try {
            CallerHelper ch = new CallerHelper();

            this.request.put("terminos", "terminos");
            this.request.put("aceptaterminos", "SI");
            this.request.put("identificacionterminos", user);
            this.request.put("documentoterminos", this.rutaTerminos);

            Response resp = ch.login(this.request, user, pass);

            TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) resp.get("TSAFEUSERDETAIL");
            manageloginresponse(tsafeUserDetail);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("TSAFEUSERDETAIL", tsafeUserDetail);
            if (tsafeUserDetail.getChangepassword().equalsIgnoreCase("N")) {
                FacesContext ctx = FacesContext.getCurrentInstance();
                ExternalContext externalContext = ctx.getExternalContext();
                NavigationHandler handler = ctx.getApplication().getNavigationHandler();
                handler.handleNavigation(ctx, null, "workspace");

                externalContext.redirect(externalContext.getRequestContextPath() + "/" + "pages/workspace.xhtml");

                this.request.setBrowser(obtainBrowserName((String) externalContext.getRequestHeaderMap().get("User-Agent")));
                this.request.setOperativesystem(obtainSOName((String) externalContext.getRequestHeaderMap().get("User-Agent")));

                changeprofile();
            } else {
                ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
                ec.redirect(ec.getRequestContextPath() + "/" + "change-password.xhtml");
                System.out.println("debe cambiar la clave : " + ec.getRequestContextPath() + "/" + "passwordExpired.xhtml");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void authenticateCas(String username, String urlCasLogout)
            throws Throwable {
        try {
            this.casLogoutUrl = urlCasLogout;
            this.request.put("login", username);
            CallerHelper ch = new CallerHelper();
            Response resp = ch.loginCas(this.request, username, null);
            if (resp.getResponseCode().compareTo("0") == 0) {
                TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) resp.get("TSAFEUSERDETAIL");
                manageloginresponse(tsafeUserDetail);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("TSAFEUSERDETAIL", tsafeUserDetail);

                changeprofile();
            } else {
                throw new Exception(resp.getResponseCode() + " " + resp.getResponseUserMessage());
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public void updateusesession() {
        System.out.println("logout::cerrando session");
        try {
            CallerHelper ch = new CallerHelper();
            ch.logout(this.request);
        } catch (Throwable e) {
        }
    }

    public String logout() {
        System.out.println("logout::cerrando session bean");
        updateusesession();
        FacesContext fc = FacesContext.getCurrentInstance();
        if (fc != null) {
            fc.getExternalContext().invalidateSession();
        }
        return "/login?faces-redirect=true";
    }

    private void manageloginresponse(TsafeUserDetail userdetail) {
        this.mlocation.put("cia", userdetail.get("cn"));
        this.mlocation.put("branch", userdetail.get("bn"));
        this.mlocation.put("office", userdetail.get("on"));
        this.mlocation.put("area", userdetail.get("an"));
        this.mlocation.put("channel", userdetail.get("chn"));
        this.mlocation.put("accodate", userdetail.get("ad"));
        this.mlocation.put("workdate", userdetail.get("wd"));
        this.mlocation.put("nickname", userdetail.getNickname());
        this.mlocation.put("sbsemployee", userdetail.get("sbsemployee"));
        this.mlocation.put("sbsusercode", userdetail.get("sbsusercode"));
        obtenerCentroControl(userdetail);
        obtenerUnidadControl(userdetail);
        this.request.setUser(userdetail.getPk().getUsercode());
        this.request.setCompany(userdetail.getCompanycode());
        this.request.setBranchCode(userdetail.getBranchcode());
        this.request.setOfficeCode(userdetail.getOfficecode());
        this.request.setChannelCode(userdetail.getChannelcode());
        this.request.setLanguage(userdetail.getLanguagecode());
        this.request.setCentrocontrol(userdetail.getCcentrocontrol());
        this.changepassword = userdetail.getChangepassword();
        this.lprofile = ((List) userdetail.get("lprofile"));
        this.request.setProfile(((TsafeUserProfile) this.lprofile.get(0)).getPk().getProfilecode());
    }

    private void obtenerCentroControl(TsafeUserDetail userdetail) {
        TgeneCatalogDetail tcentrocontrol = null;
        try {
            TarmCentroControl centroControl = CentroControlArmasController.findPorCodigo(userdetail.getCcentrocontrol());
            if (centroControl != null) {
                tcentrocontrol = CatalogDetailController.findCatalogo(centroControl.getInstituciontipo(), centroControl.getInstitucion());
            }
        } catch (CommondbException e) {
        } catch (Exception e) {
        }
        if (tcentrocontrol != null) {
            userdetail.addAddtionalInfo("centrocontrol", tcentrocontrol.getDescription());
            this.mlocation.put("centrocontrol", tcentrocontrol.getDescription());
        } else {
            userdetail.addAddtionalInfo("centrocontrol", "");
            this.mlocation.put("centrocontrol", "");
        }
    }

    private void obtenerUnidadControl(TsafeUserDetail userdetail) {
        TgeneCatalogDetail unidad = null;
        try {
            TarmCentroControl centroControl = CentroControlArmasController.findPorCodigo(userdetail.getCcentrocontrol());
            if (centroControl != null) {
                unidad = CatalogDetailController.findCatalogo(centroControl.getNombreinstitucioncodigo(), centroControl.getNombreinstitucion());
            }
        } catch (CommondbException e) {
        } catch (Exception e) {
        }
        if (unidad != null) {
            userdetail.addAddtionalInfo("unidad", unidad.getDescription());
            this.mlocation.put("unidad", unidad.getDescription());
        } else {
            userdetail.addAddtionalInfo("unidad", "");
            this.mlocation.put("unidad", "");
        }
    }

    public void changeprofile()
            throws Exception {
        try {
            this.ldocumentoscaducarse = new ArrayList<>();

            if (this.profilecode != null) {
                this.request.setProfile(this.profilecode);
                //generarAlertaArmas();
            }
            
            CallerHelper ch = new CallerHelper();
            Response resp = ch.menu(this.request);
            if (resp.getResponseCode().compareTo("0") == 0) {
                Map<String, Object> rootmenu = (Map) resp.get("rootmenu");
                List<Map<String, Object>> lmenu = (List) rootmenu.get("items");
                this.maiaMenu.buildMenu(lmenu);
            } else {
                MessageHelper.setMessageError(resp);
            }
            alertarPermisosCaducarse(); //alerta para permisos prontos a caducarse

        } catch (Throwable e) {
            e.printStackTrace();
            MessageHelper.setMessageError(e);
        }
    }
    
    
    /**
     * PERMISOS PROXIMOS A CADUCARSE
     */
    private void alertarPermisosCaducarse() throws Exception{
            ldocumentoscaducarse = new ArrayList<>();
            TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("TSAFEUSERDETAIL");
            TcustPersonDetail personaSesion = buscarPersonaSesion();
            PersonAddressController direccionController = new PersonAddressController();

            TcustPersonAddress tcustPersonAddres = direccionController.findPrincipal(tsafeUserDetail.getPk().getPersoncode().toString());
            TcustPersonDetail personaPermiso = null;
                if(personaSesion != null && tcustPersonAddres.getProvincecode() != null 
                        && profilecode != null && !profilecode.equals("24")&& !profilecode.equals("25")){
                     TgeneParameters param = ParametersController.find("DIASPREVIOSCADUCAR", "1");
                    TarmCentroControlJur jurisdiccionCentro = TarmCentroControlJurController.findxProvincia(tcustPersonAddres.getProvincecode());
                    int numeroDias = param != null ? param.getNumbervalue().intValue() : 5;
                    List<TarmDocumentoHabilitante>lstDocs = DocumentoHabilitanteController.
                            findByCcontrolCercaCaducarse(jurisdiccionCentro.getCcentrocontrol(),numeroDias+"");
                    
                    TgeneProvince provinciaJurisdicion = ProvinceController.findPorCodigo(jurisdiccionCentro.getCountrycode(), jurisdiccionCentro.getProvincecode()).get(0);
                    
                    if(lstDocs != null && !lstDocs.isEmpty()){
                        MessageHelper.setMessageInfo(String.format("Permisos prontos a caducarse en la jurisdiccion %s.",provinciaJurisdicion.getDescription()));

                        for (TarmDocumentoHabilitante doc : lstDocs) {

                            personaPermiso = PersonDetailController.find(doc.getPersoncode().toString());
                            doc.getModifiedData().put("identificacion", personaPermiso!= null ? personaPermiso.getIdentification() : "");
                            doc.getModifiedData().put("nombre", personaPermiso != null ? personaPermiso.getName() : "" );
                            doc.getModifiedData().put("jurisdiccion", provinciaJurisdicion.getDescription()!= null ? provinciaJurisdicion.getDescription() : "");
                            ldocumentoscaducarse.add(doc);
                            MessageHelper.setMessageInfo(String.format("Documento %s, perteneciente a %s expira el %s.",doc.getNumerodocumento(), personaPermiso.getName(), doc.getFechaexpiracion()));
 
                        }
                        //RequestContext.getCurrentInstance().execute("PF('advicesDialog').show()");
                    }
                }
    }
    
    
    /**
     * GENERA ALERTA DE MAXIMO DE ARMAS
     * unicamente en el perfil de CLIENTE
    */
    private void generarAlertaArmas(){
        
        if(profilecode != null && profilecode.equals("24")){
            List <TarmSolicitud> lstSolicitudes = SolicitudController.findSolicitudxPersona(buscarPersonaSesion().getPk().getPersoncode().toString());
            if(lstSolicitudes != null && !lstSolicitudes.isEmpty()){
                for (TarmSolicitud sol : lstSolicitudes) {
                    validarArmas(sol);
                }
            }
        }
        
    }
    /**
     * VALIDA ARMAS POR SOLICITUD
     * que no posea mas armas que las que el tipo de tramite lo tiene permitido
     */
    private void validarArmas(TarmSolicitud solicitud){
        TarmTramite tramite = TarmTramiteController.findSimple(solicitud.getCtramite().toString());
        int maxArmas = tramite.getNumeromaxarmas() != null ? tramite.getNumeromaxarmas().intValue() : 0;
        List<TarmDocumentoHabilitante>lstDocs = DocumentoHabilitanteController.findByCsolicitud(solicitud.getPk(),"APR");
        int narmas = 0;
        if(lstDocs != null && !lstDocs.isEmpty()){
            String[] armas = new String[lstDocs.size()];
            for (int i = 0; i < lstDocs.size(); i++) {
                armas[i]=lstDocs.get(i).getCarma();
            }
            narmas = eliminarDuplicados(armas).size();
            
        }

        if(tramite.getNumeromaxarmas() != null && narmas > maxArmas){
            MessageHelper.setMessageWarn(String.format("La solicitud %s posee %s armas registradas, Máximas permitidas %s", solicitud.getNumerosolicitud(),narmas, maxArmas));
        }
        
    }
    
    /**
     * Eliminar elementos duplicados jdk7
     */
   
    public static List<String> eliminarDuplicados(String[] arreglo){
        List<String> arregloLista = Arrays.asList(arreglo);
        Set<String> hashSet = new HashSet<String>(arregloLista);
        arregloLista.clear();
        arregloLista.addAll(hashSet);
        return arregloLista;
    }
    
    /**
     * OBTENER PERSONA DE USUARIO LOGEADO
     */
    
    private TcustPersonDetail buscarPersonaSesion(){
        TcustPersonDetail person = null;
        try {
            TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("TSAFEUSERDETAIL");
            person = PersonDetailController.find(tsafeUserDetail.getPk().getPersoncode().toString());

        } catch (Exception e) {
            MessageHelper.setMessageError(String.format("Verifique que el usuario este asociado a una persona: %s", e.getMessage()));
        }
        return person;
    }
    
    
    
    private void fillCompanies() {
        try {
            CallerHelper ch = new CallerHelper();
            Request request = new Request();
            DtoQuery dto = new DtoQuery(null, null, null, true, null);

            HashMap<String, DtoQuery> mtables = new HashMap();
            mtables.put("CIAS", dto);
            request.setCompany(Integer.valueOf(1));
            request.getModifiedData().put("queryalias", "COMPANY");
            request.setQueryTables(mtables);

            Response resp = ch.executeQuery(request);
            if (resp.getResponseCode().compareTo("0") != 0) {
                this.lcompany = new ArrayList();
                MessageHelper.setMessageError(resp);
            } else {
                this.lcompany = ((List) resp.get("CIAS"));
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    public void fijaRequestData(Request request, String transactionmodule, Integer transactioncode, Integer transactionversion)
            throws Exception {
        request.setCompany(this.request.getCompany());
        request.setCentrocontrol(this.request.getCentrocontrol());
        request.setUnidad(this.request.getUnidad());
        request.setBranchCode(this.request.getBranchCode());
        request.setOfficeCode(this.request.getOfficeCode());
        request.setUser(this.request.getUser());
        request.setLanguage(this.request.getLanguage());
        request.setChannelCode(this.request.getChannelCode());
        request.setTerminalCode(this.request.getTerminalCode());
        request.setProfile(this.request.getProfile());
        request.setBrowser(this.request.getBrowser());
        request.setOperativesystem(this.request.getOperativesystem());

        request.setTransactionModule(transactionmodule);
        request.setTransactionCode(transactioncode);
        request.setTransactionVersion(transactionversion);
    }

    private String obtainBrowserName(String userAgent) {
        if (userAgent.contains("MSIE")) {
            return buildBrowser(userAgent, "MSIE");
        }
        if (userAgent.contains("Firefox")) {
            return buildBrowser(userAgent, "Firefox");
        }
        if (userAgent.contains("Chrome")) {
            return buildBrowser(userAgent, "Chrome");
        }
        if (userAgent.contains("Opera")) {
            return buildBrowser(userAgent, "Opera");
        }
        if (userAgent.contains("Safari")) {
            return buildBrowser(userAgent, "Safari");
        }
        return "Unknown";
    }

    private String obtainSOName(String userAgent) {
        String os = "";
        if (userAgent.contains("Windows")) {
            os = buildOS(userAgent, "Windows");
        } else if (userAgent.contains("Mac")) {
            os = buildOS(userAgent, "Mac");
        } else if (userAgent.contains("Linux")) {
            os = buildOS(userAgent, "Linux");
        } else if (userAgent.contains("android")) {
            os = buildOS(userAgent, "android");
        } else if (userAgent.contains("iphone")) {
            os = buildOS(userAgent, "iphone");
        } else {
            os = "UnKnown, More-Info: " + userAgent;
        }
        return os;
    }

    private String buildBrowser(String userAgent, String id) {
        String browser = "";
        if (userAgent.contains("MSIE")) {
            String[] value = userAgent.substring(userAgent.indexOf(id), userAgent.length()).split(" ");
            browser = value[0] + " " + value[1];
        } else {
            String[] value = userAgent.substring(userAgent.indexOf(id), userAgent.length()).split(" ");
            browser = value[0];
        }
        return browser;
    }

    private String buildOS(String userAgent, String id) {
        String so = "";
        if (userAgent.contains("Windows")) {
            String[] value = userAgent.substring(userAgent.indexOf(id), userAgent.length()).split(" ");
            so = value[0] + " " + value[1] + " " + value[2];
        } else {
            String[] value = userAgent.substring(userAgent.indexOf(id), userAgent.length()).split(" ");
            so = value[0] + " " + value[1];
        }
        return so;
    }

    public List<Map<String, Object>> getLcompany() {
        return this.lcompany;
    }

    public void setLcompany(List<Map<String, Object>> lcompany) {
        this.lcompany = lcompany;
    }

    public List<TsafeUserProfile> getLprofile() {
        return this.lprofile;
    }

    public void setLprofile(List<TsafeUserProfile> lprofile) {
        this.lprofile = lprofile;
    }

    public String getChangepassword() {
        return this.changepassword;
    }

    public void setChangepassword(String changepassword) {
        this.changepassword = changepassword;
    }

    public Map<String, Object> getMdata() {
        return this.mdata;
    }

    public void setMdata(Map<String, Object> mdata) {
        this.mdata = mdata;
    }

    public Request getRequest() {
        return this.request;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public MaiaMenu getMaiaMenu() {
        return this.maiaMenu;
    }

    public void setMaiaMenu(MaiaMenu maiaMenu) {
        this.maiaMenu = maiaMenu;
    }

    public Map<String, Object> getMlocation() {
        return this.mlocation;
    }

    public boolean isRenderBpmData() {
        return this.renderBpmData;
    }

    public void setRenderBpmData(boolean renderBpmData) {
        this.renderBpmData = renderBpmData;
    }

    public String getCasLogoutUrl() {
        return this.casLogoutUrl;
    }

    public void setCasLogoutUrl(String casLogoutUrl) {
        this.casLogoutUrl = casLogoutUrl;
    }

    public String getProfilecode() {
        return this.profilecode;
    }

    public void setProfilecode(String profilecode) {
        this.profilecode = profilecode;
    }

    public void help()
            throws Exception {
        String m = this.request.getTransactionModule();
        String t = this.request.getTransactionCode().toString();
        String v = this.request.getTransactionVersion().toString();
        String p = ParametersController.find(EnumParametros.PATH_ALFRESCO_AYUDA.getCodigo(), this.request.getCompany().toString()).getTextvalue();
        RequestContext.getCurrentInstance().execute("Maiaworkspace.loadHelp('" + m + "', '" + t + "', '" + v + "', '" + p + "')");
    }

    @PreDestroy
    private void closeSessionMaia() {
        try {
            FacesContext fc = FacesContext.getCurrentInstance();
            if (fc != null) {
                logout();
            }
        } catch (Exception e) {
        }
    }

    public String getRutaTerminos() {
        return this.rutaTerminos;
    }

    public void setRutaTerminos(String rutaTerminos) {
        this.rutaTerminos = rutaTerminos;
    }

    public StreamedContent getContent() {
        return this.content;
    }

    public void setContent(StreamedContent content) {
        this.content = content;
    }

    public boolean isAlertaInicio() {
        return alertaInicio;
    }

    public void setAlertaInicio(boolean alertaInicio) {
        this.alertaInicio = alertaInicio;
    }
    
     /**
     * Permisos a punto de caducarse
     * @return 
     */
    public List<TarmDocumentoHabilitante> getLdocumentoscaducarse() {
        return ldocumentoscaducarse;
    }

    public void setLdocumentoscaducarse(List<TarmDocumentoHabilitante> ldocumentoscaducarse) {
        this.ldocumentoscaducarse = ldocumentoscaducarse;
    }
    

    /**
     * ACCION AL CERRARSE EL MODAL DE PERMISOS A CADUCARSE
     */
    public void onHidePermisosCaducarse() {
        System.out.println("Hide dialog advices");
        //ldocumentoscaducarse = new ArrayList<>();
    }
    
    
}
