package org.josast.propertyHttp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.logging.Logger;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

/**
 * @author christophe
 * 
 * This class read a properties file from an URL.
 * 
 *
 */
public class ConfigHttp {
	private Logger log = Logger.getLogger(getClass().getName());
	private String url = "";
	private Properties props = new Properties();
	private boolean connected = false;

	/**
	 * @param url URL of the properties file to read 
	 */
	public ConfigHttp(String url) {
		super();
		this.url = url;
		loadProperties();
	}

	/**
	 * Load the properties file and initialise Properties field
	 */
	private void loadProperties() {

		final String USER_AGENT = "Mozilla/5.0";

		HttpClient client = HttpClientBuilder.create().build();
		HttpGet request = new HttpGet(url);
		request.addHeader("User-Agent", USER_AGENT);
		HttpResponse response;
		try {
			response = client.execute(request);

			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

			props.load(rd);
			connected = true;
		} catch (ClientProtocolException e) {
			log.severe("Error read URL");
			e.printStackTrace();
		} catch (IOException e) {
			log.severe("Error read URL ");
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param Item property name 
	 * @return property value, null if property not found
	 */
	public String GetProperty(String Item) {

		if (props != null) {
			String S = props.getProperty(Item);
			if (S == null)
			{
				return null;
			}
				else
				{
				return S.trim(); // $NON-NLS-1$
				}
		}
		return null;

	}
	
	/**
	 * @return true if the Property file has been read
	 */
	public boolean isConnected() {
		return connected;
	}

	
	
	public static void main(String[] args) {
		ConfigHttp c = new ConfigHttp("http://site.amsat-f.org/download/116451");
		System.out.println(c.GetProperty("EntrySatVersion"));
	}



}
