#!/usr/bin/env python3.4

import json
import urllib.parse
import urllib.request
from pprint import pprint

API_URL = "https://tone-analyzer-demo.mybluemix.net/tone"



def query_watson(message):
    """Given the message extracted from the SQLite 3 database, returns the
    JSON generated by IBM Watson"""
    message_list = message.split("\n")
    result_dict = {}
    for message in chunks(message_list):
        data = {"text": message}
        data = urllib.parse.urlencode(data)
        binary_data = data.encode("UTF-8")
        req = urllib.request.Request(API_URL, binary_data)
        response = urllib.request.urlopen(req)
        the_page = response.read()
        result_dict.update(json.loads(the_page.decode()))
        #print()
        #pprint(result_dict)
        #print()
    return result_dict


def chunks(l, n=200):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i+n]


def gen_emotions_dict(emotions_dict):
    """Given the emotions sub-dict from the page response, generates and
    returns an emotions dict composed of each emotion, as well as the
    count of words for that emotion and the percentage of them with
    respect to the total"""
    emotions_dict = emotions_dict["children"][0]
    emotions_list = emotions_dict["children"]
    total_emotions = emotions_dict["word_count"]
    emotions_stats = {}
    for emotion in emotions_list:
        emotion_name = emotion["name"]
        emotion_count = emotion["word_count"]
        try:
            emotion_percentage = (emotion_count / total_emotions) * 100
        except ZeroDivisionError:
            emotion_percentage = 0
        emotions_stats[emotion_name] = {}
        emotions_stats[emotion_name]["word_count"] = emotion_count
        emotions_stats[emotion_name]["percentage"] = emotion_percentage
    return emotions_stats
