# Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License

import matplotlib.pyplot as plt
import pandas
import numpy

pandas.options.display.max_rows = 300


def leaflet_plot_stations(size, filename):
    dataframe = pandas.read_csv('data/C2A2_data/BinnedCsvs_d400/{}.csv'.format(
        filename), usecols=['Date', 'Element', 'Data_Value'])
    dataframe['Year'], dataframe['MonthDay'] = zip(
        *dataframe['Date'].apply(lambda x: (x[:4], x[5:])))
    dataframe = dataframe[dataframe['MonthDay'] != '02-29']
    min_all = dataframe[(dataframe['Element'] == 'TMIN') & (
        dataframe['Year'] != '2015')].groupby('MonthDay')['Data_Value'].min()
    max_all = dataframe[(dataframe['Element'] == 'TMAX') & (
        dataframe['Year'] != '2015')].groupby('MonthDay')['Data_Value'].max()
    min_2015 = dataframe[(dataframe['Element'] == 'TMIN') & (
        dataframe['Year'] == '2015')].groupby('MonthDay')['Data_Value'].min()
    max_2015 = dataframe[(dataframe['Element'] == 'TMAX') & (
        dataframe['Year'] == '2015')].groupby('MonthDay')['Data_Value'].max()
    broken_min = numpy.where(min_2015.values < min_all.values)[0]
    broken_max = numpy.where(max_2015.values > max_all.values)[0]
    plt.plot(min_all.values)
    plt.plot(max_all.values)
    ax = plt.gca()
    ax.xaxis.grid()
    ax.yaxis.grid()
    fig = plt.gcf()
    DPI = fig.get_dpi()
    fig.set_size_inches(4 * size / float(DPI), 2 * size / float(DPI))
    plt.xlabel('Days')
    plt.ylabel('Temperature')
    plt.title('Temperature in Tenths of Degrees in Celsius')
    plt.xticks(range(0, len(min_all), 5),
               min_all.index[range(0, len(min_all), 5)], rotation=45)
    plt.scatter(broken_min, min_2015.iloc[broken_min], c='r')
    plt.scatter(broken_max, max_2015.iloc[broken_max], c='g')
    plt.legend(['Minimum', 'Maximum', 'Broken Low', 'Broken High'])
    plt.fill_between(range(len(min_all)), min_all.values,
                     max_all.values, color='grey', alpha='0.1')
    plt.show()
