from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.clock import Clock, mainthread
import asyncio
from bleak import BleakClient, BleakError
import threading

Window.size = (720, 600)

class CustomDropDown(DropDown):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.auto_width = False
        self.width = Window.width
        self.max_height = 200

    def add_widget(self, widget):
        if isinstance(widget, Button):
            widget.halign = 'center'
            widget.valign = 'middle'
            widget.text_size = (None, None)
            widget.bind(size=self.update_button_padding, texture_size=self.update_button_padding)
            widget.bind(text=self.update_button_padding)
        super().add_widget(widget)

    def update_button_padding(self, button, *args):
        button.text_size = (button.width, None)
        button.texture_update()
        button.padding_x = (button.width - button.texture_size[0]) / 2

class GetAccGyrodata_app(App):
    def build(self):
        self.counts = {1: 0, 2: 0, 3: 0, 4: 0}
        self.data_buffer = {"S": None, "V": None}
        self.is_sleeping = False
        self.client = None

        main_layout = FloatLayout()

        self.mainbutton = Button(
            text='MENU', size_hint=(1, None),
            height=75, pos_hint={'top': 1}
        )
        main_layout.add_widget(self.mainbutton)

        self.dropdown = CustomDropDown()

        sleep_btn = Button(text='SLEEP', size_hint_y=None, height=40)
        sleep_btn.bind(on_release=self.sleep)
        self.dropdown.add_widget(sleep_btn)

        quit_btn = Button(text='QUIT', size_hint_y=None, height=40)
        quit_btn.bind(on_release=self.stop)
        self.dropdown.add_widget(quit_btn)

        self.mainbutton.bind(on_release=self.open_dropdown)
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.mainbutton, 'text', x))

        self.status_label = Label(text='Connecting to device...', size_hint=(1, None), font_size=48, pos_hint={'top': 0.9})
        self.smash_label = Label(text='Waiting for data...', size_hint=(1, None), font_size=48, pos_hint={'top': 0.7})
        self.speed_label = Label(text='', size_hint=(1, None), font_size=48, pos_hint={'top': 0.5})
        self.reps_label = Label(text='', size_hint=(1, None), font_size=48, pos_hint={'top': 0.3})

        main_layout.add_widget(self.status_label)
        main_layout.add_widget(self.smash_label)
        main_layout.add_widget(self.speed_label)
        main_layout.add_widget(self.reps_label)

        return main_layout

    def open_dropdown(self, widget):
        self.dropdown.open(widget)

    def sleep(self, instance):
        print("Entering sleep mode...")
        self.is_sleeping = True
        self.update_status_label("Sleeping...")
        # Disconnect the BLE client if connected
        if self.client and self.client.is_connected:
            asyncio.run_coroutine_threadsafe(self.client.disconnect(), asyncio.get_event_loop())

    def wakeup(self):
        print("Waking up from sleep mode...")
        self.is_sleeping = False
        self.update_status_label("Reconnecting...")
        asyncio.run_coroutine_threadsafe(self.reconnect(), asyncio.get_event_loop())

    def stop(self, *args):
        self.running = False
        if self.client:
            asyncio.run_coroutine_threadsafe(self.client.disconnect(), asyncio.get_event_loop())
        App.get_running_app().stop()

    def on_start(self):
        self.running = True
        threading.Thread(target=self.bleak_thread, daemon=True).start()

    def bleak_thread(self):
        asyncio.run(self.connect_and_receive_data())

    async def connect_and_receive_data(self):
        DEVICE_ADDRESS = "E6:B0:FA:69:60:0B"
        UART_RX_CHARACTERISTIC_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

        while self.running:
            if self.is_sleeping:
                await asyncio.sleep(1)
                continue

            try:
                self.client = BleakClient(DEVICE_ADDRESS, disconnected_callback=self.on_disconnected)
                await self.client.connect()
                if not self.client.is_connected:
                    print("Unable to connect to the device!")
                    self.update_status_label("Disconnected from device")
                    await asyncio.sleep(5)
                    continue

                print(f"Connected to device with address {DEVICE_ADDRESS}!")
                self.update_status_label("Connected to device")

                def handle_notification(char_uuid, data):
                    if self.running and not self.is_sleeping:
                        decoded_data = data.decode()
                        print(f"Received data: {decoded_data}")  # Print received data to terminal
                        self.process_received_data(decoded_data)

                await self.client.start_notify(UART_RX_CHARACTERISTIC_UUID, handle_notification)

                print("Receiving data...")
                while self.running and not self.is_sleeping:
                    await asyncio.sleep(1)

                await self.client.stop_notify(UART_RX_CHARACTERISTIC_UUID)
                print("Disconnected from device.")
                self.update_status_label("Disconnected from device")

            except BleakError as e:
                print(f"Error: {str(e)}")
                self.update_status_label("Disconnected from device")
                await asyncio.sleep(5)

    def on_disconnected(self, client):
        if self.is_sleeping:
            return
        print("Device was disconnected, callback activated.")
        self.update_status_label("Disconnected from device")
        if self.running and not self.is_sleeping:
            asyncio.run_coroutine_threadsafe(self.reconnect(), asyncio.get_event_loop())

    async def reconnect(self):
        while self.running and not self.is_sleeping:
            try:
                print("Attempting to reconnect...")
                self.client = BleakClient("E6:B0:FA:69:60:0B", disconnected_callback=self.on_disconnected)
                await self.client.connect()
                if self.client.is_connected:
                    print("Reconnected successfully!")
                    self.update_status_label("Reconnected to device")

                    def handle_notification(char_uuid, data):
                        if self.running and not self.is_sleeping:
                            decoded_data = data.decode()
                            print(f"Received data: {decoded_data}")  # Print received data to terminal
                            self.process_received_data(decoded_data)

                    await self.client.start_notify("6E400003-B5A3-F393-E0A9-E50E24DCCA9E", handle_notification)
                    return
            except BleakError as e:
                print(f"Reconnect error: {str(e)}")
            await asyncio.sleep(5)

    @mainthread
    def update_status_label(self, status):
        self.status_label.text = status

    def process_received_data(self, data):
        print(f"Processing data: {data}")  # Debugging statement to print data to terminal
        if "S:" in data:
            number = int(data.split("S:")[1].split("-")[0])
            self.data_buffer["S"] = number
        elif "V:" in data:
            speed = data.split("V:")[1].split("-")[0]
            self.data_buffer["V"] = speed

        if self.data_buffer["S"] is not None and self.data_buffer["V"] is not None:
            self.update_data_label()

    @mainthread
    def update_data_label(self):
        number = self.data_buffer["S"]
        speed = self.data_buffer["V"]

        if number in self.counts:
            self.counts[number] += 1

        smash_type = ['Smash', 'Net', 'Drive', 'Lift'][number - 1]
        smash_text = smash_type if smash_type else "unmeasurable"
        speed_text = f"Speed: {speed}km/h" if speed else "unmeasurable"
        reps_text = f"Reps: {self.counts[number]}"

        self.smash_label.text = smash_text
        self.speed_label.text = speed_text
        self.reps_label.text = reps_text

        # Clear the status label once data is received
        self.status_label.text = ""

        # Clear the buffer
        self.data_buffer = {"S": None, "V": None}

if __name__ == "__main__":
    GetAccGyrodata_app().run()
