import sensors
from gui.mainWindow import MainWindow

import time
import threading
import queue
import configparser
import tkinter as tk
import traceback

conf = configparser.ConfigParser()
conf.read('config.ini')

class CalibrationStateMashine():

  def __init__(self):
    self.state = 0
    self.value_count = 0

    self.NOT_CALIBRATED = 0
    self.WAITING_POS_1  = 1
    self.ACCUMULATING_1 = 2
    self.WAITING_POS_2  = 3
    self.ACCUMULATING_2 = 4
    self.CALIBRATION_DONE = 5

  def state_clearname(self):
    if self.state == self.NOT_CALIBRATED:
      return "not calibrated"
    elif self.state == self.WAITING_POS_1:
      return "Waiting for Position one"
    elif self.state == self.ACCUMULATING_1:
      return "gathering values on position one"
    elif self.state == self.WAITING_POS_2:
      return "Waiting for position two"
    elif self.state == self.ACCUMULATING_2:
      return "gathering values on position two"
    elif self.state == self.CALIBRATION_DONE:
      return "calibration done"
    
  def next_state(self):
    if self.state < self.CALIBRATION_DONE:
      self.state += 1
      print(self.state_clearname())

  def next_state_gui(self):
    print("next_state_gui",self.state)
    if self.state == self.WAITING_POS_1 or self.state == self.WAITING_POS_2:
      self.next_state()

  def get_state(self):
    return self.state

  def reset_state(self):
    self.state = 0


def main():
  up_queue = queue.Queue()
  down_queue = queue.Queue()
  calibration_state = CalibrationStateMashine()
  ac_sensor = sensors.AcusticSensor(conf,up_queue,down_queue,calibration_state)
  sensor_thread = threading.Thread(target=ac_sensor.start)

  try:
    sensor_thread.start()
    root = tk.Tk()
    root.title("Tracking System")
    view = MainWindow(root,up_queue,down_queue,calibration_state)
    view.pack(side="top", fill="both", expand=True)
    view.update()
    root.mainloop()

  except KeyboardInterrupt:
    print("stop")
  except Exception as e:
    print("Error: ",e)
    traceback.print_exc()
  finally:
    down_queue.put("stop")

main()