
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AppContext {
	public static final String SKM_APP_LOGGER_NAME = "com.videonext.skm";
	private Logger logger = Logger.getLogger(SKM_APP_LOGGER_NAME);

	private static AppContext instance;

	private String masterHost = "";
	private String user = "";
	private Session session = new Session();
	private boolean secureTransport = false;

	protected AppContext() {
	}

	public static synchronized AppContext getInstance() {
		if (instance == null) {
			instance = new AppContext();
		}
		return instance;
	}

	public Logger getLogger() {
		return logger;
	}

	public String getMasterHost() {
		return masterHost;
	}

	public String getSessionId() {
		return session.getSessionId();
	}

	public Session getSession() {
		return session;
	}

	public String getUser() {
		return user;
	}

	public boolean init(String masterHost, String user, String password) {

		AppContext context = AppContext.getInstance();
		boolean loginCompleted = false;

		try {
			System.out.println("Connecting to '"+masterHost+"'");
			context.session.open(masterHost, user, password);
			context.masterHost = masterHost;
			context.user = user;
			loginCompleted = true;
		} catch (Exception e) {
			// TODO : make some output
			System.err.println("Failed to connect!");
			e.printStackTrace();
		}
		
		System.out.println("Login successful : " + session.getSessionId());
		return loginCompleted;
	}

	public void destroy() {
		if (session != null) {
			session.close();
		}
	}

	public Document getAPICallDocument(String relativePath) throws Exception {
		AppContext context = AppContext.getInstance();

		String urlStr = (secureTransport ? "https" : "http") + "://"
				+ context.getMasterHost() + relativePath;

		URL objlistURL = new URL(urlStr);
		URLConnection urlConnection = objlistURL.openConnection();
		urlConnection.setUseCaches(false);
		session.addSessionCookie(urlConnection);
		urlConnection.connect();
		Document doc = null;

		// parse response
		//
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();

		doc = documentBuilder.parse(urlConnection.getInputStream());
		Element docElement = doc.getDocumentElement();

		// parse request status
		//
		NodeList nl = docElement.getElementsByTagName("STATUS");
		if (nl != null && nl.getLength() > 0) {
			Element statusElement = (Element) nl.item(0);
			String status = statusElement.getAttribute("VALUE");

			if (status == null) {
				throw new Exception(
						"Failed to get request status: missing attribute STATUS.VALUE");
			} else if (!status.equalsIgnoreCase("OK")) {
				String msg = statusElement.getAttribute("MESSAGE");
				throw new Exception("Failed to get resource list: "
						+ ((msg == null) ? "unknown error" : msg));
			}
		}
		return doc;

	}

	protected void finalyze() {
		destroy();
	}
}
