package com.ejie.ad74a.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.ejie.ad74a.exception.Ad74aException;
import com.ejie.ad74a.exception.BatchProcessException;

/**
 * Clase de utilidades de seguridad para recuperar el token de XLNets de una
 * aplicacion
 * 
 * @author PPE
 */
public final class UtilTokenXlnets {

	private static final Logger LOGGER = LoggerFactory.getLogger(UtilTokenXlnets.class);

//	public static final List<String> GRUPOS_TECNICOS = Arrays 
//			.asList(new String[] { "AD74A-GU-0002", "AD74A-GU-0006", "AD74A-GU-0004", "AD74A-GU-0005" });
	public static final List<String> GRUPOS_TECNICOS = Arrays.asList(new String[] { "AD74A-GU-0001", "AD74A-GU-0008" });

	/**
	 * 'UtilTokenXlnets'
	 */
	private UtilTokenXlnets() {
	}

	/**
	 * Obtiene el token xl-nets (formato String) desde el entorno back-end en ejie
	 * 
	 * @return String
	 * @throws BatchProcessException
	 * 
	 */
	public static String getTokenStringXLNets(String idAplic) {
		UtilTokenXlnets.LOGGER.trace("getTokenStringXLNets INI {}", idAplic);
		
		/**** CODIGO A RESTITUIR ES PARA QUE FUNCIONE CLIENTE THIN Y REGALADOR DE TOKENS A LA VEZ ****/
		//if (Boolean.parseBoolean(UtilProperties.Props.EN_OFICINA.val())) {
		if (!"".equals(UtilProperties.Props.EN_OFICINA_TOKEN.val())) {
			// XXX Se asigna un token de pruebas
			return UtilProperties.Props.EN_OFICINA_TOKEN.val();
		} else {
			try {// Se descarga el token de un servlet regalador de tokens.
				URL url = new URL(UtilProperties.Props.N38_TOKEN_URL.val() + idAplic);
				URLConnection conn = url.openConnection();

				BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				StringBuilder result = new StringBuilder();
				String line;
				while ((line = rd.readLine()) != null) {
					result.append(line);
				}
				rd.close();
				return result.toString();
			} catch (IOException e) {
				throw new Ad74aException("getTokenStringXLNets", e);
			}
		}
	}

	/**
	 * Devuelve un objeto Document con el token de sesion
	 * 
	 * @param idAplic {@link String}
	 * @return {@link String}
	 */
	public static Document getTokenDocumentXLNets(String idAplic) {
		Document result;
		DocumentBuilder builder;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			// [jbhg] deshabilitar acceso a entidades externas (brecha de seguridad)
			factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new Ad74aException("getTokenDocumentXLNets, ", e);
		}
		try {
			// result = builder.parse(getTokenApp()); --> parametro String NO
			result = builder.parse(new InputSource(new StringReader(getTokenStringXLNets(idAplic))));
		} catch (IOException | SAXException e) {
			throw new Ad74aException("getTokenDocumentXLNets, ", e);
		}

		result.getDocumentElement().normalize();
		return result;
	}

}