package org.josast.SIDS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import org.apache.log4j.Logger;

/**
 * @author christophe
 *
 */
public class HttpPostSIDS {

	static Logger logger = Logger.getLogger(HttpPostSIDS.class);

	private static String USER_AGENT = "Mozilla/5.0";

	HttpClient client = null;
	HttpPost post = null;
	StringBuffer result = null;

	public HttpPostSIDS(String url) {

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

	}

	public int SendSIDSBasic(SIDSData sids) {
		// Data preparation
		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);

		}
		int resultat = 0;
		HttpResponse response = null;
		BufferedReader rd = null;
		try {
			response = client.execute(post);
			resultat = response.getStatusLine().getStatusCode();

		} 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;
	}

}
