import numpy as np
import scipy.io
import os
import sys
import time
if sys.version_info[0] == 3 and sys.version_info[1] >= 8:
	from typing import TypedDict
else:
	from typing_extensions import TypedDict


class Entry(TypedDict):
	variable: str
	name: str
	unit: str


class Tracer:
	def __init__(self, obj, var_list: Entry, name='default', path='./logs'):
		if not os.path.exists(path):
			os.makedirs(path)
		self.obj = obj
		self.var_list = var_list
		self.timestamp = 0
		self.timestamp_data = np.empty(0)
		self.filename_full = os.path.join(path, '') + name + "." + time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".mat"
		self.filename = os.path.join(path, '') + name + ".mat"
		self.data_list = {}
		for var in self.var_list:
			self.data_list[var['name']] = np.empty(0)

	def process(self):
		data = {}
		self.timestamp_data = np.append(self.timestamp_data, self.timestamp)
		data['time'] = self.timestamp_data

		for var in self.var_list:
			key_name = var['name']
			key_variable = var['variable']
			self.data_list[key_name] = np.append(self.data_list[key_name], self.obj.__getattribute__(key_variable))
			data[key_name] = self.data_list[key_name]

		scipy.io.savemat(self.filename, data)
		scipy.io.savemat(self.filename_full, data)
		self.timestamp += 1


class Test:
	def __init__(self):
		self.a = 0
		self.b = 0

	def process(self):
		self.a += 1
		self.b += 10

	@staticmethod
	def get_entry():
		a: Entry = [{'variable': 'a', 'name' : 'v_a', 'unit': 'u_a'}]
		b: Entry = [{'variable': 'b', 'name' : 'v_b', 'unit': 'u_b'}]
		return a + b


if __name__ == '__main__':
	test = Test()

	dut = Tracer(test, Test.get_entry(), name='TracerTest')

	for i in range(0, 10):
		dut.process()
		test.process()
