import tkinter as tk
from tkinter.ttk import Progressbar

class CalibrationPopUp(tk.Frame):
  def __init__(self, root, calibration_state):
    self.root = root
    self.calibration_state = calibration_state
    tk.Frame.__init__(self, root)
    self.pendingClose = False

    self.instruction = tk.Label(self,text="Start Calibration", anchor="c",font=("Helvatica", 18, 'bold'))
    self.instruction.pack(side="top", fill="both", expand=True)
    button = tk.Button(self,text="OK", command=self.calibration_state.next_state_gui, anchor="c",height=1,width=5)
    button.pack(side="top", fill="both", expand=True)
    self.cs = Progressbar(self, orient='horizontal', mode='determinate')
    self.cs.pack(side="top", fill="both", expand=True)

    root.bind('<Escape>', self.close)
  
  def update(self):
    if not self.root.winfo_exists():
      return

    self.cs['value'] = self.calibration_state.progress
    if self.calibration_state.get_state() == self.calibration_state.WAITING_POS_1:
      self.instruction["text"] = "Move gondola to far left corner!"
    elif self.calibration_state.get_state() == self.calibration_state.WAITING_POS_2:
      self.instruction["text"] = "Move gondola to far right corner!"
    elif self.calibration_state.get_state() == self.calibration_state.CALIBRATION_DONE and not self.pendingClose:
      self.pendingClose = True
      self.root.after(1500, self.close)
    elif self.calibration_state.get_state() == self.calibration_state.CALIBRATION_DONE:
      self.instruction["text"] = "Calibration Done!"
    else:
      self.instruction["text"] = "Processing..."

  def close(self):
    if self.root.winfo_exists():
      self.root.destroy()