import matplotlib
matplotlib.use('Agg')  # This must be at the top of the file due to magic reasons

from decimal import Decimal  # noqa
import os  # noqa
import matplotlib.pyplot as plt  # noqa
from django.conf import settings  # noqa
from .models import VariableReport  # noqa

plt.style.use('ggplot')


def make_chart(var):
    raw_data = VariableReport.objects.filter(variable_id=var).values(
        'variable_id', 'log_date', 'good_max', 'good_min', 'okay_max', 'okay_min', 'bad_max', 'bad_min', 'count', 'count_avg', 'nu_avg', 'dashboard_status')
    make_timeseries_chart(var, raw_data)
    return


def make_timeseries_chart(variable, raw_data):
    big_filename = '{0}.png'.format(variable.id)
    thumb_filename = '{0}_thumb.png'.format(variable.id)
    big_output_path = os.path.join(settings.MEDIA_ROOT, big_filename)
    thumb_output_path = os.path.join(settings.MEDIA_ROOT, thumb_filename)
    log_dates = list(map(lambda d: d['log_date'], raw_data))
    # log_dates = [dt.datetime.strptime(d, '%Y').date() for d in log_dates_raw]
    counts = list(map(lambda d: d['count'], raw_data))
    counts_avg = list(map(lambda d: d['count_avg'], raw_data))
    nus_avg = list(map(lambda d: d['nu_avg'], raw_data))
    good_min = list(map(lambda d: d['good_min'] - Decimal('0.5'), raw_data))
    okay_min = list(map(lambda d: d['okay_min'] - Decimal('0.5'), raw_data))

    if variable.type == 'bo' or variable.type == 'te':
        plt.plot(log_dates, counts, 'ko', label=variable.name)
        axes = plt.gca()
        axes.set_ylim([0, 7])
    elif variable.type == 'co':
        plt.plot(log_dates, counts_avg, 'ko', label=variable.name)
    elif variable.type == 'me':
        plt.plot(log_dates, nus_avg, 'ko', label=variable.name)
    elif variable.type == 'di':
        return
    else:
        raise Exception

    plt.plot(log_dates, good_min, color='green')
    plt.plot(log_dates, okay_min, color='red')
    plt.ylabel('Total days per week {0} (rolling count)'.format(variable))
    fig = plt.gcf()
    fig.set_size_inches(8, 6)
    plt.savefig(big_output_path)
    fig.set_size_inches(1, 0.5)
    plt.savefig(thumb_output_path)
    plt.clf()
