# required:
# - pip install matplotlib (need apt python-pip)
# - sudo apt-get install python-gi-cairo


import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import matplotlib.pyplot as plt  
import numpy as np
from datetime import datetime
import time

from matplotlib.backends.backend_gtk3agg import (
    FigureCanvasGTK3Agg as FigureCanvas)

# load numpy array from csv file
from numpy import loadtxt, savetxt

class Window1Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()
        
    def on_hscrollbar1_value_changed(self, widget):
        print ("scollbar changed")


def main():
    builder = Gtk.Builder()
    builder.add_objects_from_file("hscroll.glade", ("window1", ""))
    builder.connect_signals(Window1Signals())
    window = builder.get_object("window1")
    al = builder.get_object("alignment1")
    sb = builder.get_object("hscrollbar1")
    

    # load data
    try:
        data = loadtxt('stats.txt', delimiter=',', ndmin=2)

    except IOError:
        print("[View stats:] No file found")
        data = np.array([[0,0,0,0]])
        
    # limit display to last n entries
    max_disp = 10
    labels = data[-max_disp:,0]
    motion_time = data[-max_disp:,1]/3600
    spindle_time = data[-max_disp:,2]/3600
    travel_dist = data[-max_disp:,3]/1000
    
    # format x-labels
    labeltext = []
    for x in labels:
        #labeltext.append(datetime.fromtimestamp(x).strftime('%m/%d'))
        labeltext.append(datetime.utcfromtimestamp(x).strftime('%m/%d'))

    # Start of Matplotlib specific code

    x = np.arange(len(labels))  # the label locations
    width = 0.3  # the width of the bars

    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx() 

    rects1 = ax1.bar(x - width*0.8, motion_time, width, label='Time in move', color='orange')
    rects2 = ax1.bar(x , spindle_time, width, label='Spindle time', color='green')
    rects3 = ax2.bar(x + width*0.8, travel_dist, width, label='Travel distance', color='blue')

    # Add some text for labels, title and custom x-axis tick labels, etc.
    ax1.set_ylabel('Time (h)')
    ax2.set_ylabel('Distance (m)')
    #ax1.set_title('Scores by group and gender')
    ax1.set_xticks(x)
    ax1.set_xticklabels(labeltext)

    #ax1.legend(loc='upper left')
    #ax2.legend(loc='upper right')
    fig.legend(loc='upper center', ncol=3)
    
    # use this for displaying without glade:
    #plt.show()
    
    canvas = FigureCanvas(fig)  # a Gtk.DrawingArea
    canvas.set_size_request(800, 500)
    al.add(canvas)


    # End of Matplotlib specific code
    


    window.show_all()
    Gtk.main()

if __name__ == "__main__":
    main()
