package artistmetrics;

import java.io.File;
import java.net.*;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

public class ServerConnection {
	private String configUsername = null;
	private String configPassword = null;
	private String configUrl = null;
	private String cookie = null;
	
	public ServerConnection() throws Exception {
		readConfig();
		login();
		
		if(cookie == null)
			throw new Exception("Invalid username or password!");
	}
	
	public void sendMetric(String type, Map<String, String> data)
	{
		//Construct the query string.
		String connectionString = "type=" + type;
		for(Map.Entry<String, String> me : data.entrySet())
			connectionString += "&" + me.getKey() + "=" + me.getValue();
		
		String connectionURL = configUrl + "Record.action?" + connectionString;
		
		try {
			URL url = new URL(connectionURL);
			URLConnection conn = url.openConnection();

			HttpURLConnection httpConn = (HttpURLConnection)conn;
	        httpConn.setInstanceFollowRedirects(false);
			
			//Yummy - Regurgitated cookie.
			httpConn.setRequestProperty("Cookie", cookie);
			
			conn.connect();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Document getAllMetrics()
	{
		//Construct the query string.
		String connectionURL = configUrl + "MetricsXML.action";
		
		try {
			URL url = new URL(connectionURL);
			URLConnection conn = url.openConnection();

			HttpURLConnection httpConn = (HttpURLConnection)conn;
	        httpConn.setInstanceFollowRedirects(false);
			
			//Yummy - Regurgitated cookie.
			httpConn.setRequestProperty("Cookie", cookie);
			
			conn.connect();
			
			return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(conn.getInputStream());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private void login() throws Exception {
		String connectionURL = configUrl + "Login.action?username=" + configUsername + "&password=" + configPassword;

        // Create a URLConnection object for a URL
        URL url = new URL(connectionURL);
        URLConnection conn = url.openConnection();
    
        //We need to disable redirects so that we can nom on the cookie.
        HttpURLConnection httpConn = (HttpURLConnection)conn;
        httpConn.setInstanceFollowRedirects(false);
    
        // Send the request to the server
        conn.connect();
        
        //nom nom cookie nom.
        cookie = httpConn.getHeaderField("Set-Cookie");
        
        if(cookie == null)
        	throw new Exception("Invalid username/password.");
	}
	
	private void readConfig() {
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	    
			//Create an instance of the XML document in memory.
			Document doc = docBuilder.parse (new File("configuration.xml"));
	        doc.getDocumentElement ().normalize ();
	        NodeList nl = doc.getDocumentElement().getChildNodes();
	        
	        //Iterate through the children to find what we're looking for.
	        for(int i = 0; i < nl.getLength(); i++) {
	        	Node n = nl.item(i);
	            	
	        	if(n.getNodeName() == "username")
	        		configUsername = n.getTextContent();
	        	else if(n.getNodeName() == "password")
	        		configPassword = n.getTextContent();
	        	else if(n.getNodeName() == "URL")
	        		configUrl = n.getTextContent();	
	        }
	            
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		new ServerConnection();
	}
}
