import os
import sys
import inspect
import numpy as np
import datetime as dt
import time
import pytz
import pandas as pd
import pdb
import tmpo
#import charts

from opengrid import config
from opengrid.library import houseprint

c=config.Config()
DEV = c.get('env', 'type') == 'dev' # DEV is True if we are in development environment, False if on the droplet

if not DEV:
    # production environment: don't try to display plots
    import matplotlib
    matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator, DateFormatter, AutoDateLocator

try:
    if os.path.exists(c.get('tmpo', 'data')):
        path_to_tmpo_data = c.get('tmpo', 'data')
except:
    path_to_tmpo_data = None

if DEV:
    if c.get('env', 'plots') == 'inline':
        %matplotlib inline
    else:
        %matplotlib qt
else:
    pass # don't try to render plots
plt.rcParams['figure.figsize'] = 12,8

"""
Explanation: This script shows how to use the existing code in opengrid to create a baseload electricity consumption benchmark.
End of explanation
"""


number_of_days = 7

"""
Explanation: Script settings
End of explanation
"""


hp = houseprint.load_houseprint_from_file('new_houseprint.pkl')
hp.init_tmpo(path_to_tmpo_data=path_to_tmpo_data)

start = pd.Timestamp(time.time() - number_of_days*86400, unit='s')

sensors = hp.get_sensors()
#sensors.remove('b325dbc1a0d62c99a50609e919b9ea06')

for sensor in sensors:
    s = sensor.get_data(head=start, resample='s')
    try:    
        s = s.resample(rule='60s', how='max')
        s = s.diff()*3600/60

        # plot with charts (don't show it) and save html

        charts.plot(pd.DataFrame(s), stock=True, 
                    save=os.path.join(c.get('data', 'folder'), 'figures', 'TimeSeries_'+sensor.key+'.html'), show=True)
    except:
        pass

len(sensors)

"""
Explanation: We create one big dataframe, the columns are the sensors
End of explanation
"""


