package artistmetrics.actions;

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

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import artistmetrics.LoginForm;

public class ServerConnection {
	private String configUsername = null;
	private String configPassword = null;
	private String configUrl = null;
	private String cookie = null;
	
	public ServerConnection() throws Exception {
		LoginForm frm = new LoginForm();
		
		if(frm.getSuccess())
		{
			configUsername = frm.getUsername();
			configPassword = frm.getPassword();
			configUrl = frm.getServer();
		}
		
		//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();
            
            if(httpConn.getResponseCode() != 200)
            {
                System.out.println("Error occurred while sending data to the server: " + httpConn.getResponseMessage());
            }
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
        catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	public Document getAllMetrics()
	{
		//Construct the query string.
		String connectionURL = configUrl + "MetricsXML.action";
		System.out.println("URL: " + connectionURL);
		
		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();
        
        System.out.println("Connection to " + connectionURL);
    
        //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.");
	}
	
	public static void main(String[] args) throws Exception {
		new ServerConnection();
	}
}
