"""CSC110 Fall 2020 Course Project: Transformation and Analysis of Scraped Data

Authors: Michele Massa, Nischal Nair, Nathan Zavys-Cox

Description: this module contains functions that conduct the necessary procedures to
transform the json file generated by our Scrapy spider, and analysing how and what
will be output to the user based on the predicted CO2 behaviours.

This file is copyright (c) 2020 Michele Massa, Nischal Nair and Nathan Zavys-Cox."""

from typing import Any, List, Dict
import json
from compute_results import co2_increase_rate, determine_algorithm, ma_period_cls, run_related_rates, run_wma
from read_data import get_all_data

#################################################################################################################
################
# Disease Data #
################
#################################################################################################################

# Scrappy generated file: disease_data.json


def read_disease_data(file: str) -> Dict[str, List[str]]:
    """Return a dictionary mapping disease_name to key facts from the data in the disease_data.json file,
    which is a file generated using scrapy to scrape data from WHO websites regarding respiratory diseases.

    In the returned dictionary:
        - each key is a string representing the disease
        - each corresponding value is a list of strings, where each string is a key fact about the disease.

    Preconditions:
        - file is the path to a JSON file containing disease data, name of the file is: 'disease_data.json'.
    """
    with open(file) as json_file:
        data = json.load(json_file)

    # Generates a list of lists, with each inner list item being a fact about a disease.
    key_fact_data = [data[i]['key_facts'] for i in range(0, len(data))]

    # ACCUMULATOR: keeps track of the disease to key_fact list dictionary
    key_facts_so_far = {}

    for key_fact in key_fact_data:

        if 'Asthma' in key_fact[0]:
            key_facts_so_far['Asthma'] = key_fact
        elif 'Pneumonia' in key_fact[0]:
            key_facts_so_far['Pneumonia'] = key_fact
        else:
            key_facts_so_far['Chronic Obstructive Pulmonary Disease'] = key_fact

        # The chosen keywords that should be in the first element of the inner list of key_facts_data
        # were chosen based on the json file we generated through scrappy, so This is not a general function,
        # but rather a function made specifically for this json file.

    return key_facts_so_far


def output_disease_data_condition(country: str) -> bool:
    """ Determine whether the user-input country, based on WMA predicted CO2 emission values is more
    likely to contract one of the 3 most common respiratory diseases due to pollution than before.

    The procedure here is that rather than actually looking at the CO2 values themselves, we look at
    the rate of change over the 5 predicted years, if the average of these rates of change is >100(tonnes),
    then True is returned.

    >>> output_disease_data_condition('Canada')
    False
    """

    data = get_all_data()

    # Determine which method to use, based on slopes
    country_dict = {country: data[country]}
    n = ma_period_cls(country_dict)
    past_increase_rate = co2_increase_rate(country, n)

    if determine_algorithm(past_increase_rate) == 'RR':
        future_co2 = run_related_rates(country)
        keys = list(future_co2.keys())
        value_dict = future_co2[keys[0]]
        value_list = [value_dict[i][1] for i in range(0, len(value_dict))]  # Get values out of year to value tuple
        usable_list = value_list[len(value_list) - n - 1: len(value_list)]  # slice list to get useful yearly values

    else:
        future_co2 = run_wma(country)
        value_list = [future_co2[i][1] for i in range(0, len(future_co2))]  # Get values out of year to value tuple
        usable_list = value_list[len(value_list) - n - 1: len(value_list)]  # slice list to get useful yearly values

    # ACCUMULATOR: keeps track of the rates of change between the values in usable_list
    roc_so_far = []

    for i in range(0, len(usable_list) - 1):
        roc_so_far.append(usable_list[i + 1] - usable_list[i])

    average_co2_future_rate = sum(roc_so_far) / len(roc_so_far)

    if average_co2_future_rate < 25:
        return False

    return True


def output_disease_data(condition: bool) -> Any:
    """ Depending on the value of the condition returns two different messages to the user:
        - message 1: warns user about the increasing CO2 levels in the chosen country and returns key facts
        about respiratory illnesses that are more likely to be contracted when exposed to air pollution.
        - message 2: doesn't warn user about anything as the chosen country CO2 predicted values don't
        show the required behaviour.
    """
    message_1 = "The chosen country has shown worrying CO2 emission level increase. Here's some key facts " \
                "about some diseases people in these countries might be more likely to contract in the future."
    message_2 = "The chosen country doesn't show a serious increase in CO2 levels in the future years. Lets " \
                "keep it that way."

    if condition is False:
        return message_2

    key_facts = read_disease_data('disease_data.json')  # this is the file with the disease information
    key_fact1 = key_facts['Asthma']
    key_fact2 = key_facts['Pneumonia']
    key_fact3 = key_facts['Chronic Obstructive Pulmonary Disease']

    return ([message_1], key_fact1, key_fact2, key_fact3)


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(config={
        'max-line-length': 120,
        'extra-imports': ['python_ta.contracts', 'compute_results', 'json', 'read_data', 'typing'],
        'allowed-io': ['read_disease_data'],
        'disable': ['C0200', 'R0914', 'E9988', 'E9969']
    })

    import python_ta.contracts

    python_ta.contracts.DEBUG_CONTRACTS = False
    python_ta.contracts.check_all_contracts()

    import doctest

    doctest.testmod()
