package de.hsadmin.core.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class TicketValidator {

	private static TicketValidator instance;
	
	private String proxyValidateURL;
	private String proxyServiceURL;
	
	private TicketValidator() {
		proxyServiceURL = null;
		proxyValidateURL = null;
	}
	
	public static TicketValidator getInstance() {
		if (instance == null) {
			instance = new TicketValidator();
		}
		return instance;
	}
	
	public void initialize(String validateURL, String serviceURL) {
		proxyServiceURL = serviceURL;
		proxyValidateURL = validateURL;
	}
	
	public String validateTicket(String ticket) throws AuthenticationException {
		// for testing purpose only
		if ("TestUmgebung".equals(proxyServiceURL) && "TestUmgebung".equals(proxyValidateURL)) {
			if (ticket.startsWith("user:")) {
				return ticket.substring(5);
			} else {
				throw new AuthenticationException("Invalid Ticket: " + ticket);
			}
		}
		// real implementation
		if (proxyServiceURL == null || proxyValidateURL == null) {
			throw new RuntimeException("TicketValidator is not initialized.");
		}
		try {
			URL url = new URL(proxyValidateURL + "?service=" + proxyServiceURL + "&ticket=" + ticket);
			URLConnection httpConnection = url.openConnection();
			httpConnection.connect();
			InputStream inputStream = httpConnection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			String nextLine = reader.readLine();  
			while (nextLine != null) {
				if (nextLine.contains("<cas:user>")) {
					String user = extractUser(nextLine);
					inputStream.close();
					return user;
				}
				nextLine = reader.readLine();
			}
			inputStream.close();
			throw new AuthenticationException("Invalid Ticket: " + ticket);
		} catch (MalformedURLException e) {
			throw new AuthenticationException(e.getMessage());
		} catch (IOException e) {
			throw new AuthenticationException(e.getMessage());
		}
	}

	private String extractUser(String nextLine) {
		int start = nextLine.indexOf("<cas:user>");
		int end = nextLine.indexOf("</cas:user>");
		String user = nextLine.substring(start + 10, end);
		return user;
	}

}
