import tkinter as tk
import time
import queue

import gui.Popup as Popup
import gui.graph as Graph

class MainWindow(tk.Frame):
  def __init__(self, root, up_queue, down_queue,calibration_state):
    self.root = root
    self.popup = None
    self.calibration_state = calibration_state
    self.down_queue = down_queue
    self.up_queue = up_queue
    tk.Frame.__init__(self, root)

    self.graph = Graph.Graph(self)
    self.graph.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)

    self.controls = tk.Frame(self)
    self.controls.pack(fill=tk.BOTH, side=tk.RIGHT)

    self.ac_dro_x = tk.StringVar()
    self.ac_dro_y = tk.StringVar()
    tk.Label(self.controls, text="Acustic Sensor", anchor="c").pack(side="top", fill="both", expand=False)
    tk.Label(self.controls, textvariable=self.ac_dro_x, anchor="nw").pack(side="top", fill="both", expand=False)
    tk.Label(self.controls, textvariable=self.ac_dro_y, anchor="nw").pack(side="top", fill="both", expand=False)

    calibrate_button = tk.Button(self.controls,text="calibrate",command=self.calibrate)
    calibrate_button.pack(side="top", fill="both")

  def update(self):
    ac_data = []
    while self.up_queue.qsize() > 0:
      name, data = self.up_queue.get()
      if name == "ac_data":
        ac_data.append(data)
    if len(ac_data) > 0:
      self.graph.update([ac_data])
      self.ac_dro_x.set("X: {:3.1f} mm".format(ac_data[-1][0]))
      self.ac_dro_y.set("Y: {:3.1f} mm".format(ac_data[-1][1]))

    if self.popup:
      if self.calibration_state.get_state() == self.calibration_state.CALIBRATION_DONE and not self.popup.killed:
        self.popup.killed = True
        self.root.after(1500,self.kill_popup)
      self.popup.update()
    self.root.after(30, self.update)

  def kill_popup(self):
    self.pu_root.destroy()
    self.popup = None

  def calibrate(self):
    self.down_queue.put("calibrate")
    if not self.popup:
      self.pu_root = tk.Tk()
      self.pu_root.title("Calibration")
      self.pu_root.geometry("500x200")
      self.popup = Popup.CalibrationPopUp(self.pu_root,self.up_queue,self.down_queue,self.calibration_state)
      self.popup.pack(side="top", fill="both", expand=True)
    
    
if __name__ == "__main__":
  root = tk.Tk()
  up_queue = queue.Queue()
  down_queue = queue.Queue()
  root.title("Tracking System")
  view = MainWindow(root,up_queue,down_queue,list())
  view.pack(side="top", fill="both", expand=True)
  view.update()
  root.mainloop()