package com.ejie.ab63.util;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.ejie.ab63.comun.Constantes;
import com.sun.org.apache.xpath.internal.XPathAPI;

import n38c.exe.N38API;

/**
 * Clase que gestionar los permisos de xlnets
 * 
 *  
 */

public class PermisosXLNETS {

	private static String GIVENNAME = "GIVENNAME";
	private static String SURNAME = "SURNAME";
	private static String SERIALNUMBER = "SERIALNUMBER";
	private static String COMERCIALNAME = "O";
	private static String CN = "CN";

	// private static Document documento;

	/**
	 * Constructor
	 */
	private PermisosXLNETS() {
		super();
	}

	/**
	 * Obtener token
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return Document
	 */
	public static Document fncObtenerToken(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		return n38API.n38ItemSesion();
	}

	/**
	 * Recupera los perfiles definidos para el usuario
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String[]: Array de strings con los nombres de los perfiles
	 *         definidos para el usuario
	 * @throws Exception
	 */

	public static String[] fncItemSesion(HttpServletRequest request) {

		N38API n38API = new N38API(request);
		// Número de usuarios
		String[] strUsuario = new String[Constantes.MAGIC_NUMBER_100];
		try {
			NodeList nodeLi;

			String filtro = "//parent::elemento/parametro[@id=\"n38perfiles\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);

			for (int i = 0; i < nodeLi.getLength(); ++i) {
				if (!nodeLi.item(i).getNodeValue().equals("")) {
					strUsuario[i] = nodeLi.item(i).getNodeValue();
				}
			}
		} catch (Exception e) {
			e.getMessage();
		}
		return strUsuario;

	}// fin fncItemSesion

	/**
	 * Devuelve el id del usuario
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String: Id del usuario
	 * @throws Exception
	 */

	public static String fncIdUsuario(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		String strUsuario = null;
		try {
			NodeList nodeLi;
			String filtro = "//parent::elemento/parametro[@id=\"n38personauid\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();
		} catch (Exception e) {
			return strUsuario;
		}

	}// fin fncIdUsuario

	/**
	 * retorna el subject de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncSubject(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		NodeList nodeLi = null;
		try {
			String filtro = "//parent::elemento/parametro[@id=\"n38subjectcert\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();
		} catch (Exception e) {
			return nodeLi.toString();
		}
	}

	/**
	 * retorna los apellidos de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncApellidos(HttpServletRequest request) {
		Map<String, String> mapa = PermisosXLNETS.mapaSubject(request);
		return mapa.get(PermisosXLNETS.SURNAME);
	}// fin fncApellidos

	/**
	 * mapaSubject
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return HashMap
	 */
	public static HashMap<String, String> mapaSubject(HttpServletRequest request) {
		String strSubject = PermisosXLNETS.fncSubject(request);
		String arrSubject[] = strSubject.split(",");
		HashMap<String, String> mapa = new HashMap<String, String>();
		for (int i = 0; i < arrSubject.length; i++) {
			if (((String) arrSubject[i]).indexOf("=") > 0) {
				StringTokenizer token = new StringTokenizer(arrSubject[i], "=");// NOPMD
				mapa.put(token.nextToken().trim(), token.nextToken().trim());
			}
		}
		return mapa;
	}

	/**
	 * retorna el dni completo
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncDniConLetra(HttpServletRequest request) {

		HashMap<String, String> mapa = PermisosXLNETS.mapaSubject(request);
		return mapa.get(PermisosXLNETS.SERIALNUMBER);

	}

	/**
	 * Retorna la raz�n social de la entidad
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 */
	public static String fncEntidad(HttpServletRequest request) {
		HashMap<String, String> mapa = PermisosXLNETS.mapaSubject(request);
		return (String) mapa.get(PermisosXLNETS.COMERCIALNAME);
	}

	/**
	 * retorna el dni de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncDni(HttpServletRequest request) {

		N38API n38API = new N38API(request);
		NodeList nodeLi = null;
		try {
			String filtro = "//parent::elemento/parametro[@id=\"dni\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();
		} catch (Exception e) {

			return nodeLi.toString();
		}

	}

	/**
	 * retorna el puestoUid - mailbox de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncPuestoUid(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		NodeList nodeLi = null;
		try {
			String filtro = "//parent::elemento/parametro[@id=\"n38puestouid\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();
		} catch (Exception e) {

			return nodeLi.toString();
		}
	}

	/**
	 * retorna el subject de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncIdSesion(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		NodeList nodeLi = null;
		try {
			String filtro = "//parent::elemento/parametro[@id=\"n38uidsesion\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();
		} catch (Exception e) {
			return nodeLi.toString();
		}
	}

	/**
	 * retorna la politica de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fnccertificadopoliticas(HttpServletRequest request) {

		N38API n38API = new N38API(request);
		NodeList nodeLi = null;
		;
		try {

			String filtro = "//parent::elemento/parametro[@id=\"n38certificadopoliticas\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();

		} catch (Exception e) {
			return nodeLi.toString();
		}
	}

	/**
	 * retorna el nombre de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncNombre(HttpServletRequest request) {
		HashMap<String, String> mapa = PermisosXLNETS.mapaSubject(request);
		return (String) mapa.get(PermisosXLNETS.GIVENNAME);
	}

	/**
	 * retorna el nombre completo
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncNombreCompleto(HttpServletRequest request) {

		HashMap<String, String> mapa = PermisosXLNETS.mapaSubject(request);
		return (String) mapa.get(PermisosXLNETS.CN);
	}

	/**
	 * retorna el dni de la txartela
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	public static String fncLogin(HttpServletRequest request) {

		N38API n38API = new N38API(request);
		n38API.toString();
		NodeList nodeLi = null;
		try {
			String filtro = "//parent::elemento/parametro[@id=\"n38login\"]/valor/text()";
			nodeLi = XPathAPI.selectNodeList(n38API.n38ItemSesion(), filtro);
			return nodeLi.item(0).getNodeValue();
		} catch (Exception e) {
			return nodeLi.toString();
		}

	}

	public static String getUserConnected() {
		final Authentication aut = SecurityContextHolder.getContext().getAuthentication();
		String userMod = Constantes.CODIGO_APLICACION;
		if (aut != null) {
			userMod = !"".equals(aut.getName()) ? aut.getName() : userMod;
		}
		return userMod.toUpperCase();
	}

}
