package com.ejie.ab78.comun;

import java.io.Serializable;
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.ab78.clientesWS.ab61WebService.Usuario;
import com.ejie.x38.security.UserCredentials;
import com.sun.org.apache.xpath.internal.XPathAPI;

import n38c.exe.N38API;

public class UtilUsuario implements Serializable {
	private static final long serialVersionUID = -2475753367190285685L;

	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";
	
	/**
	 * Constructor
	 */
	private UtilUsuario() {
		super();
	}

	public static Usuario getUsuario(Authentication aut, HttpServletRequest httpRequest) {
		Usuario usuario = new Usuario();
		if (null != aut) {
			UserCredentials credentials = (UserCredentials) aut.getCredentials();
			usuario.setUsuario(aut.getName());
			String dni = credentials.getNif();
			String dniLetra = calcularLetra(dni);
			if (dniLetra != null) {
				usuario.setIdentificador(dniLetra);
			} else
				// Si tenemos un usuario ficticio, no tenemos NIF con lo que
				// pondremos el Nombre en el Identificador
				usuario.setIdentificador(usuario.getUsuario());
			if (credentials.getName() != null) {
				usuario.setNombreUsuario(credentials.getName());
			}
			if (credentials.getSurname() != null && !"".equals(credentials.getSurname())) {
				usuario.setPrimerApellido(credentials.getSurname());
			}
			usuario.setBuzon(UtilsXlnets.obtenerLogin(httpRequest));
		}
		return usuario;
	}
	
	private static String calcularLetra(String dni) {
		String caracteres = "TRWAGMYFPDXBNJZSQVHLCKE";
		String dniLetra = null;
		try {
			int resto = Integer.parseInt(dni) % 23;
			dniLetra = dni + caracteres.charAt(resto);
		} catch (NumberFormatException e) {
			dniLetra = null;
		}
		return dniLetra;
	}

	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();
	}
	
	public static HashMap<String, String> mapaSubject(HttpServletRequest request) {
		String strSubject = UtilUsuario.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;
	}
	
	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();
		}
	}
	
	public static String fncNombre(HttpServletRequest request) {
		HashMap<String, String> mapa = UtilUsuario.mapaSubject(request);
		return (String) mapa.get(UtilUsuario.GIVENNAME);
	}
	
	public static String fncApellidos(HttpServletRequest request) {
		Map<String, String> mapa = UtilUsuario.mapaSubject(request);
		return mapa.get(UtilUsuario.SURNAME);
	}
	
	public static String fncNombreCompleto(HttpServletRequest request) {

		HashMap<String, String> mapa = UtilUsuario.mapaSubject(request);
		return (String) mapa.get(UtilUsuario.CN);
	}
	
	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();
		}
	}
	
	public static String fncDniConLetra(HttpServletRequest request) {
		HashMap<String, String> mapa = UtilUsuario.mapaSubject(request);
		return mapa.get(UtilUsuario.SERIALNUMBER);
	}
	
	public static String fncEntidad(HttpServletRequest request) {
		HashMap<String, String> mapa = UtilUsuario.mapaSubject(request);
		return (String) mapa.get(UtilUsuario.COMERCIALNAME);
	}
	
	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;
		}
	}
	
	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();
		}
	}
	
	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();
		}
	}
	
	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();
		}
	}
	
	public static String[] fncItemSesion(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		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;
	}
	
	public static Document fncObtenerToken(HttpServletRequest request) {
		N38API n38API = new N38API(request);
		return n38API.n38ItemSesion();
	}

}
