package de.ugoe.cs.autoquest.htmlmonitor;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import org.mortbay.jetty.servlet.DefaultServlet;

import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * TODO comment
 * </p>
 * 
 * @author Patrick Harms
 */
public class HtmlMonitorServlet extends DefaultServlet {

    /**  */
    private static final long serialVersionUID = 1L;
    
    /**
     * 
     */
    private HtmlMonitorMessageListener messageListener;

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param htmlMonitoringListener
     */
    HtmlMonitorServlet(HtmlMonitorMessageListener messageListener) {
        this.messageListener = messageListener;
    }

    /* (non-Javadoc)
     * @see org.mortbay.jetty.servlet.DefaultServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        Object value = null;
        try {
            value = JSONValue.parseWithException(new InputStreamReader(request.getInputStream()));
            
            if (!(value instanceof JSONObject)) {
                Console.printerrln("incoming data is not of the expected type --> discarding it");
            }
            else {
                handleJSONObject((JSONObject) value);
            }
        }
        catch (ParseException e) {
            Console.printerrln
                ("could not parse incoming data --> discarding it (" + e.toString() + ")");
        }
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param object
     */
    private void handleJSONObject(JSONObject object) {
        dumpJSONObject(object, "");
        
        JSONObject message = assertValue(object, "message", JSONObject.class);
        
        if (message == null) {
            Console.printerrln("incoming data is no valid message --> discarding it");
        }
        else {
            HtmlClientInfos clientInfos = extractClientInfos(message);

            if (clientInfos == null) {
                Console.printerrln
                    ("incoming message does not contain valid client infos --> discarding it");
            }
            else {
                HtmlEvent[] events = extractHtmlEvents(message, clientInfos);
                if (events == null) {
                    Console.printerrln
                    ("incoming message does not contain valid events --> discarding it");
                }
                else {
                    messageListener.handleMessage(clientInfos, events);
                }
            }
        }
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param object
     * @return
     */
    private HtmlClientInfos extractClientInfos(JSONObject message) {
        HtmlClientInfos clientInfos = null;
        
        JSONObject infos = assertValue(message, "clientInfos", JSONObject.class);
        
        if (infos != null) {
            String clientId = assertValue((JSONObject) infos, "clientId", String.class);
            String userAgent = assertValue((JSONObject) infos, "userAgent", String.class);
            URL url = assertValue((JSONObject) infos, "url", URL.class);
            String title = assertValue((JSONObject) infos, "title", String.class);
            
            if (clientId == null) {
                Console.printerrln("client infos do not contain a valid client id");
            }
            else if (userAgent == null) {
                Console.printerrln("client infos do not contain a valid user agent");
            }
            else if (url == null) {
                Console.printerrln("client infos do not contain a valid URL");
            }
            else if (title == null) {
                Console.printerrln("client infos do not contain a valid title");
            }
            else {
                clientInfos = new HtmlClientInfos(clientId, userAgent, url, title);
            }
        }
        
        return clientInfos;
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param object
     * @param clientInfos
     * @return
     */
    private HtmlEvent[] extractHtmlEvents(JSONObject object, HtmlClientInfos clientInfos) {
        List<HtmlEvent> events = null;
        
        JSONArray eventArray = assertValue(object, "events", JSONArray.class);
        
        if (eventArray != null) {
            events = new ArrayList<HtmlEvent>();
            
            for (int i = 0; i < eventArray.size(); i++) {
                Object eventObj = eventArray.get(i);
                if (!(eventObj instanceof JSONObject)) {
                    Console.printerrln("event number " + (i + 1) + " is not a valid event object");
                }
                else {
                    Long time = assertValue(((JSONObject) eventObj), "time", Long.class);
                    String path = assertValue(((JSONObject) eventObj), "path", String.class);
                    String eventType =
                        assertValue(((JSONObject) eventObj), "eventType", String.class);
                    Integer[] coordinates =
                        assertValue(((JSONObject) eventObj), "coordinates", Integer[].class);
                    Integer key = assertValue(((JSONObject) eventObj), "key", Integer.class);
                    Integer scrollPosition =
                        assertValue(((JSONObject) eventObj), "scrollPosition", Integer.class);
                    
                    if (time == null) {
                        Console.printerrln("event number " + (i + 1) + " has no valid timestamp");
                    }
                    else if (path == null) {
                        Console.printerrln("event number " + (i + 1) + " has no valid path");
                    }
                    else if (eventType == null) {
                        Console.printerrln("event number " + (i + 1) + " has no valid event type");
                    }
                    else if ((coordinates != null) && (coordinates.length != 2)) {
                        Console.printerrln("event number " + (i + 1) + " has no valid coordinates");
                    }
                    else if (checkEventParameterCombinations
                                (eventType, coordinates, key, scrollPosition))
                    {
                        events.add(new HtmlEvent(clientInfos, time, path, eventType, coordinates,
                                                 key, scrollPosition));
                    }
                    else {
                        Console.printerrln
                            ("event number " + (i + 1) + " has no valid parameter combination");
                    }
                }
            }
            
        }
        
        if ((events != null) && (events.size() > 0)) {
            return events.toArray(new HtmlEvent[events.size()]);
        }
        else {
            return null;
        }
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param eventType
     * @param coordinates
     * @param key
     * @param scrollPosition
     * @return
     */
    private boolean checkEventParameterCombinations(String    eventType,
                                                    Integer[] coordinates,
                                                    Integer   key,
                                                    Integer   scrollPosition)
    {
        boolean result = false;
        
        if ("onscroll".equals(eventType)) {
            if ((coordinates == null) && (key == null) && (scrollPosition != null)) {
                result = true;
            }
            else {
                Console.printerrln(eventType + " event has invalid parameters");
            }
        }
        else if ("onclick".equals(eventType) || "ondblclick".equals(eventType)) {
            if ((coordinates != null) && (key == null) && (scrollPosition == null)) {
                result = true;
            }
            else {
                Console.printerrln(eventType + " event has invalid parameters");
            }
        }
        else if ("onkeypress".equals(eventType) || "onkeydown".equals(eventType) ||
                 "onkeyup".equals(eventType))
        {
            if ((coordinates == null) && (key != null) && (scrollPosition == null)) {
                result = true;
            }
            else {
                Console.printerrln(eventType + " event has invalid parameters");
            }
        }
        else if ("onfocus".equals(eventType) || "onmouseout".equals(eventType) ||
                 "onmousemove".equals(eventType) || "onunload".equals(eventType))
        {
            if ((coordinates == null) && (key == null) && (scrollPosition == null)) {
                result = true;
            }
            else {
                Console.printerrln(eventType + " event has invalid parameters");
            }
        }
        else {
            Console.printerrln("'" + eventType + "' is not a valid event type");
        }
        
        return result;
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param object
     * @param string
     * @param class1
     * @return
     */
    @SuppressWarnings("unchecked")
    private <T> T assertValue(JSONObject object, String key, Class<T> clazz) {
        Object value = object.get(key);
        T result = null;
        
        if (clazz.isInstance(value)) {
            result = (T) value;
        }
        else if (value instanceof String) {
            if (URL.class.equals(clazz)) {
                try {
                    result = (T) new URL((String) value);
                }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                    Console.printerrln("retrieved malformed URL for key '" + key + "': " + value +
                                       " (" + e.toString() + ")");
                }
            }
            else if ((int.class.equals(clazz)) || (Integer.class.equals(clazz))) {
                try {
                    result = (T) new Integer(Integer.parseInt((String) value));
                }
                catch (NumberFormatException e) {
                    Console.printerrln
                        ("retrieved malformed integer for key '" + key + "': " + value);
                }
            }
            else if ((long.class.equals(clazz)) || (Long.class.equals(clazz))) {
                try {
                    result = (T) new Long(Long.parseLong((String) value));
                }
                catch (NumberFormatException e) {
                    Console.printerrln
                        ("retrieved malformed long for key '" + key + "': " + value);
                }
            }
        }
        else if (value instanceof Long) {
            if ((int.class.equals(clazz)) || (Integer.class.equals(clazz))) {
                result = (T) (Integer) ((Long) value).intValue();
            }
        }
        else if (value instanceof JSONArray) {
            if ((int[].class.equals(clazz)) || (Integer[].class.equals(clazz))) {
                Integer[] resultArray = new Integer[((JSONArray) value).size()];
                boolean allCouldBeParsed = true;
                
                for (int i = 0; i < ((JSONArray) value).size(); i++) {
                    try {
                        if (((JSONArray) value).get(i) instanceof Long) {
                            resultArray[i] = (int) (long) (Long) ((JSONArray) value).get(i);
                        }
                        else if (((JSONArray) value).get(i) instanceof String) {
                            try {
                                resultArray[i] =
                                    (int) Long.parseLong((String) ((JSONArray) value).get(i));
                            }
                            catch (NumberFormatException e) {
                                Console.printerrln
                                    ("retrieved malformed integer array for key '" + key + "': " +
                                     value);
                        
                                allCouldBeParsed = false;
                                break;
                            }
                        }
                        else {
                            Console.printerrln
                                ("can not handle type of value in expected integer array '" + key +
                                 "': " + value);
                        }
                    }
                    catch (ClassCastException e) {
                        e.printStackTrace();
                        Console.printerrln("expected integer array for key '" + key +
                                           "' but it was something else: " + value);
                        
                        allCouldBeParsed = false;
                        break;
                    }
                }
                
                if (allCouldBeParsed) {
                    result = (T) resultArray;
                }
            }
        }
        
        return result;
    }

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     * @param object
     */
    private void dumpJSONObject(Object object, String indent) {
        if (object instanceof JSONArray) {
            boolean arrayContainsJSONObjects = false;
            for (Object arrayElem : (JSONArray) object) {
                if (arrayElem instanceof JSONObject) {
                    arrayContainsJSONObjects = true;
                    break;
                }                
            }
            
            if (arrayContainsJSONObjects) {
                System.out.println();
                System.out.print(indent);
                System.out.println('[');
                System.out.print(indent);
                System.out.print(' ');
            }
            else {
                System.out.print(' ');
                System.out.print('[');
            }
            
            int index = 0;
            for (Object arrayElem : (JSONArray) object) {
                if (index++ > 0) {
                    System.out.print(",");
                    if (arrayContainsJSONObjects) {
                        System.out.println();
                        System.out.print(indent);
                    }

                    System.out.print(' ');
                }

                dumpJSONObject(arrayElem, indent + "  ");
            }
            
            if (arrayContainsJSONObjects) {
                System.out.println();
                System.out.print(indent);
            }
            
            System.out.print(']');
        }
        else if (object instanceof JSONObject) {
            System.out.println(" {");
            
            @SuppressWarnings("unchecked")
            Set<Map.Entry<?,?>> entrySet = ((JSONObject) object).entrySet();
            
            int index = 0;
            for (Map.Entry<?,?> entry : entrySet) {
                if (index++ > 0) {
                    System.out.println(",");
                }
                System.out.print(indent);
                System.out.print("  \"");
                System.out.print(entry.getKey());
                System.out.print("\":");
                dumpJSONObject(entry.getValue(), indent + "  ");
            }
            
            System.out.println();
            System.out.print(indent);
            System.out.print('}');
        }
        else {
            System.out.print('"');
            System.out.print(object);
            System.out.print('"');
        }
    }

}
