package de.hsadmin.remote;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import de.hsadmin.core.util.Config;

public class RemoteCASHelper {

	private static String LOGIN_URL = "https://login.hostsharing.net:443/cas/v1/tickets";

	private String loginURL;
	
	public RemoteCASHelper() {
		initConfig();
	}

	private void initConfig() {
		loginURL = Config.getInstance().getProperty("loginURL", LOGIN_URL);
	}
	
	public String getGrantingTicketURL(String user) {
		String pw = Config.getInstance().getProperty(user + ".passWord", "-");
		try {
			String encodedParams = URLEncoder.encode("username", "UTF-8")
				+ "=" + URLEncoder.encode(user, "UTF-8")
				+ "&" + URLEncoder.encode("password", "UTF-8")
				+ "=" + URLEncoder.encode(pw, "UTF-8");
			return doHttpPost(loginURL, encodedParams);
		} catch (UnsupportedEncodingException e) {
			System.err.println(e.getMessage());
			return null;
		}
	}

	public String getServiceTicket(String location, String service) {
		try {
			String encodedParams = URLEncoder.encode("service", "UTF-8")
				+ "=" + URLEncoder.encode(service, "UTF-8");
			return doHttpPost(location, encodedParams);
		} catch (UnsupportedEncodingException e) {
			System.err.println(e.getMessage());
			return null;
		}
	}

	private String doHttpPost(String urlString, String encodedParams) {
		String result = null;
		try {
			URL url = new URL(urlString);
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setAllowUserInteraction(false);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
			writer.write(encodedParams);
			writer.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String ticket = reader.readLine();
			String readLine = null;
			do {
				readLine = reader.readLine();
			} while (readLine != null);
			result = connection.getHeaderField("Location");
			if (ticket != null && ticket.startsWith("ST-")) {
				result = ticket;
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
			return null;
		}
		return result;
	}
	
}
