import matplotlib.pyplot as plt
import numpy as np
from msgpack.fallback import unpackb
import requests
import array


def ext_hook(code, data):
    #if code == -47:
    print("code", code)
    if code == -51:
        print("before")
        res = np.frombuffer(data, dtype=np.int16)
        print(res)
        print("after")
        return res
    else:
        print(code)
    return 'unknown ext'


def decode(stream):
    return unpackb(stream, ext_hook=ext_hook, raw=False)


def from_file(file_name):
    with open(file_name, 'rb') as f:
        file_contents = f.read()
        print("File size", len(file_contents))
        res = decode(file_contents)
        print(res)
        plt.plot(res['values'], 'x-')
        plt.show()
    return res


def from_network(url="http://swimtrainer/api/session", start_index=0):
    r = requests.get("{}?startIndex={}".format(url, start_index))
    res = decode(r.content)
    print(res)
    plt.plot(res['timestamps'], res['values'], 'x-')
    plt.show()


def analyze(data, max_size=8*1024):
    time_stamps = data['timestamps'][:max_size]
    values = data['values'][:max_size]
    time_range_seconds = (time_stamps[-1] - time_stamps[0]) / 10
    dense_time_range_seconds = max_size / 10
    print("Time range {}, dense {} [minutes]".format(time_range_seconds / 60, dense_time_range_seconds / 60))

#from_network()
res = from_file('real_data/1593335527.st')
print(res)
#analyze(res)
