package org.josast.SIDS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.log4j.Logger;

public class HttpPostSIDS {
	private Logger logger = Logger.getLogger("EntrySatLogger");
	private static String USER_AGENT = "Mozilla/5.0";
	private CloseableHttpClient client = null;
	private HttpPost post = null;
	private StringBuffer result = null;

	/**
	 * Create a Http client for sending SIDS data. <br>
	 * exemple of URL
	 * <li>Satnogs https://db.satnogs.org/api/telemetry/
	 * 
	 * @param url Database http or https adress
	 */
	public HttpPostSIDS(String url) {

		client = getCloseableHttpClient();
		post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);

	}

	private CloseableHttpClient getCloseableHttpClient() {
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
					.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
						public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
							return true;
						}
					}).build()).build();
		} catch (KeyManagementException e) {
			logger.error("KeyManagementException in creating http client instance", e);
		} catch (NoSuchAlgorithmException e) {
			logger.error("NoSuchAlgorithmException in creating http client instance", e);
		} catch (KeyStoreException e) {
			logger.error("KeyStoreException in creating http client instance", e);
		}
		return httpClient;
	}

	/**
	 * @param sids
	 * @return
	 */
	public int SendSIDSBasic(SIDSData sids) {
		// Data preparation
		int resultat = 0;
		HttpResponse response = null;
		BufferedReader rd = null;
				
				
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("noradID", "" + sids.getNoradID()));
		urlParameters.add(new BasicNameValuePair("source", sids.getSource()));
		urlParameters.add(new BasicNameValuePair("timestamp", sids.getTimestamp()));
		urlParameters.add(new BasicNameValuePair("frame", sids.getFrame()));
		urlParameters.add(new BasicNameValuePair("locator", sids.getLocator()));
		urlParameters.add(new BasicNameValuePair("longitude", "" + sids.getLongitude()));
		urlParameters.add(new BasicNameValuePair("latitude", "" + sids.getLatitude()));
		urlParameters.add(new BasicNameValuePair("version", "2.0.2"));
 

		try {
			post.setEntity(new UrlEncodedFormEntity(urlParameters));
		} catch (UnsupportedEncodingException e) {
			logger.error("URL Encoding error", e);

		}

		try {
			response = client.execute(post);
			resultat = response.getStatusLine().getStatusCode();
			logger.info("URL Result " + resultat);
		} catch (IOException e) {
			logger.error("Cient executon error", e);
		}

		if (response != null)

		{

			try {
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			} catch (UnsupportedOperationException | IOException e) {
				logger.error("Buffer reader Exception ", e);
			}
			
			result = new StringBuffer();
			String line = "";
			try {
				while ((line = rd.readLine()) != null) {
					result.append(line);
				}
			} catch (IOException e) {
				logger.error("Error reading line from server  ", e);
			}
		}
		return resultat;

	}

	public StringBuffer getResult() {
		return result;
	}

}
