package com.izenpe.zain.cliente.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.axis.types.URI;
import org.apache.log4j.Logger;
import org.oasis_open.docs.www.dss._2004._06.oasis_dss_1_0_core_schema_wd_27_xsd.InternationalStringType;
import org.oasis_open.docs.www.dss._2004._06.oasis_dss_1_0_core_schema_wd_27_xsd.Result;
import org.oasis_open.docs.www.dss._2004._06.oasis_dss_1_0_core_schema_wd_27_xsd.VerifyResponse;

import com.safelayer.trustedx.client.smartwrapper.SmartVerifyResponse;

public class ZainUtil {

	private static final Logger log = Logger.getLogger(ZainUtil.class);

	// private static final String TIDYXML_B64 =
	// "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:dss=\"http://www.docs.oasis-open.org/dss/2004/06/oasis-dss-1.0-core-schema-wd-27.xsd\" xmlns:css=\"http://www.safelayer.com/TWS\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><xsl:output method=\"xml\"/><xsl:param name=\"indent-increment\" select=\"'  '\" /><xsl:template match=\"SOAP-ENV:* | dss:* | css:* | wsse:*\"><xsl:param name=\"indent\" select=\"'&#xA;'\"/><xsl:value-of select=\"$indent\"/><xsl:copy><xsl:copy-of select=\"@*\" /><xsl:apply-templates><xsl:with-param name=\"indent\" select=\"concat($indent, $indent-increment)\"/></xsl:apply-templates><xsl:if test=\"*\"><xsl:value-of select=\"$indent\"/></xsl:if></xsl:copy></xsl:template><xsl:template match=\"comment()|processing-instruction()\"><xsl:copy-of select=\".\"/></xsl:template><xsl:template match=\"*\"><xsl:copy-of select=\".\"/></xsl:template><!-- WARNING: this is dangerous. Handle with care --><xsl:template match=\"text()[normalize-space(.)='']\"/></xsl:stylesheet>";

	// Se lee el fichero binario.
	public static byte[] readBinaryFile(String filename) {
		byte buf[] = null;
		try {
			FileInputStream fis = new FileInputStream(filename);
			buf = new byte[fis.available()];
			DataInputStream dis = new DataInputStream(fis);
			dis.read(buf);
		} catch (IOException ex) {
			log.error("readBinaryFile(String)", ex); //$NON-NLS-1$
		}
		return buf;
	}

	// Se escribe en fichero binario.
	public static void writeBinaryFile(String destFilename, byte[] data) {
		try {
			File file = new File(destFilename);
			file.getParentFile();
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(destFilename);
			DataOutputStream dos = new DataOutputStream(fos);
			dos.write(data);
			log.info("writeBinaryFile(String, byte[]) - Fichero guardado con éxito en: " + destFilename);
		} catch (IOException ex) {
			log.error("Error - writeBinaryFile(String, byte[]): " + ex.getMessage()); //$NON-NLS-1$
		}
	}

	public static boolean isValid(SmartVerifyResponse verifyResposne) {
		VerifyResponse verifyResp = (VerifyResponse) verifyResposne.getInternalObject();
		return ZainUtil.isValid(verifyResp.getResult());
	}

	// Se comprueba si la petición tuvo éxito o no.
	private static boolean isValid(Result result) {
		URI resultMajor = result.getResultMajor();
		URI resultMinor = result.getResultMinor();

		boolean rmajor = (resultMajor != null) ? Constantes.RMAJOR_SUCCESS.equals(resultMajor.toString()) : false;
		boolean rminor = resultMinor == null || Constantes.RMINOR_SUCCESS.equals(resultMinor.toString());
		boolean isValid = rmajor && rminor;

		if (log.isDebugEnabled()) {
			if (resultMajor != null) {
				log.debug("isValid(result) - resultMajor = " + resultMajor);
			}
			if (resultMinor != null) {
				log.debug("isValid(result) - resultMinor = " + resultMinor);
			}
			InternationalStringType resultMessage = result.getResultMessage();
			if (resultMessage != null) {
				log.debug("isValid(result) - resultMessage = " + resultMessage.get_value());
			}
		}
		return isValid;
	}
	
	/**
	 * Se encarga de formatear la fecha del certificado a una forma estándar.
	 */
	public static String formatearFecha(String fech) {
		SimpleDateFormat fecha = new SimpleDateFormat(
				"yyyy-MM-dd'T'HH:mm:ss'Z'");
		Date date = null;
		try {
			date = fecha.parse(fech);
		} catch (java.text.ParseException e) {
			throw new RuntimeException("");
		}
		return date.toString();
	}

}