import tkinter as tki
from tkinter import Toplevel
import threading
import time

class TelloUI(object):
    def __init__(self, tello):
        self.tello = tello
        self.thread = None
        self.stopEvent = None  
        
        self.distance = 0.3

        self.quit_waiting_flag = False
        
        self.root = tki.Tk()
        self.panel = None

        self.btn_openPanel = tki.Button(self.root, text = 'Open Command Panel', relief = 'raised', command = self.openCmdWindow)
        self.btn_openPanel.pack(side = 'bottom', fill = 'both', expand = 'yes', padx = 10, pady = 5)
        
        self.stopEvent = threading.Event()
        
        self.root.wm_title('TELLO Controller')
        self.root.wm_protocol('WM_DELETE_WINDOW', self.on_close)

        self.sending_command_thread = threading.Thread(target = self._sendingCommand)

    def _sendingCommand(self):  
        while True:
            self.tello.send_command('command')        
            time.sleep(5)    

    def openCmdWindow(self):   
        panel = Toplevel(self.root)
        panel.wm_title('Command Panel')
        
        text1 = tki.Label(panel, text =
                  'W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n'
                  'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n'
                  'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n'
                  'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right',
                  justify = 'left')
        text1.pack(side = 'top')       

        self.btn_landing = tki.Button(panel, text = 'Land', relief = 'raised', command = self.telloLanding)
        self.btn_landing.pack(side = 'bottom', fill = 'both', expand = 'yes', padx = 10, pady = 5)

        self.btn_takeoff = tki.Button(panel, text = 'Takeoff', relief = 'raised', command = self.telloTakeOff)
        self.btn_takeoff.pack(side = 'bottom', fill = 'both', expand = 'yes', padx = 10, pady = 5)
        
        self.tmp_f = tki.Frame(panel, width = 100, height = 2)
        self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up)
        self.tmp_f.pack(side = 'bottom')
        self.tmp_f.focus_set()
        
    def telloTakeOff(self):
        return self.tello.takeoff()

    def telloLanding(self):
        return self.tello.land()
    
    def telloMoveForward(self, distance):
        return self.tello.move_forward(distance)

    def on_keypress_up(self, event):
        print(f'forward {self.distance} m')
        self.telloMoveForward(self.distance)

    def on_close(self):
        print('[INFO] closing...')
        self.stopEvent.set()
        del self.tello
        self.root.quit()