from RPi import GPIO
import time
from helpers.RFIDklasse import RFIDReader
from helpers.AfstandssensorKlasse import UltrasonicSensor
from helpers.SpeakerKlasse import BluetoothMusicPlayer
from helpers.MCP3008reader import MCP3008Reader
from helpers.klasseknop import Button
from helpers.OLEDdisplayKlasse import OLEDDisplay
from helpers.acceleroSensorKlasse import PunchSpeedSensor
from PIL import Image
import spidev
import threading
import subprocess
import queue

audio_command_queue = queue.Queue()


path_Geert ='/home/user/2023-2024-projectone-mct-Maciej-Mitura/backend/Geert.bmp'
path_Clown = '/home/user/2023-2024-projectone-mct-Maciej-Mitura/backend/clown.bmp'
path_MCT = '/home/user/2023-2024-projectone-mct-Maciej-Mitura/backend/MCT.bmp'

#-------------------------

GPIO.cleanup()

#-------------------------

GPIO.setmode(GPIO.BCM)

#TurnOffPiButton = Button(23)
punchMeter = PunchSpeedSensor()
Display = OLEDDisplay(i2c_bus=1, i2c_address=0x3C)
AfstandSens = UltrasonicSensor(13 ,26)
MCPreader = MCP3008Reader()
#button_joystick = Button(17)
#Default reset pin = 22!!!
RFIDsensor = RFIDReader()
speaker = BluetoothMusicPlayer()
#MAC Address Bluetooth speaker
MAC_Bluetooh = 'BA:89:44:1C:E8:26'
#Path to file
path_song = "/home/user/2023-2024-projectone-mct-Maciej-Mitura/backend/helpers/RoxyDaddy.mp3"
path_Oof = "/home/user/2023-2024-projectone-mct-Maciej-Mitura/backend/media/oof.mp3"
path_Countdown = "/home/user/2023-2024-projectone-mct-Maciej-Mitura/backend/media/countdown.mp3"






def TurnOffPi(channel):
    GPIO.cleanup()
    print(f"Button {channel} has been pressed...")
    print(f"Shutting down the Pi.....")
    subprocess.call(["sudo", "shutdown", "now"])


def button_pressed(channel):
    print("button_pressed_callback", channel)

#button_joystick.on_release(button_pressed)
#TurnOffPiButton.on_release(TurnOffPi)


#Read and write from/to RFID tag - hacked hehe
def hacked():
    print("Printing to RFID")
    text  = "Hacked by your favourite Pole HIHI HEHE HAHA HOHO"
    RFIDsensor.write_to_rfid(text)

    time.sleep(4)
    print("Reading from RFID")
    RFIDsensor.read_from_rfid()

# Function to perform RFID operations in a separate thread
def joystick_functions():
    while True:
        # Check for joystick event
        sens_Joystick_X = MCPreader.read_channel(4)

        #print(sens_Joystick_X)
        if sens_Joystick_X > 700:
            
            print("Clearing screen")
            
            
            time.sleep(0.1)
        if sens_Joystick_X < 350:
            RFIDsensor.read_from_rfid()
            time.sleep(0.5)
            RFIDsensor.write_to_rfid("passwordje")
                    
            

        



# Function to display an image with a delay in a separate thread
def display_image(image_path, duration):
    def display_image_worker():
        Display.display_image(image_path)
        time.sleep(duration)
        

    thread = threading.Thread(target=display_image_worker)
    thread.start()

def display_text(text,duration):
    def display_text_worker():
        Display.write_text(text)
        time.sleep(duration)

    thread = threading.Thread(target=display_text_worker)
    thread.start()


def clear_screen():
    def clear_screen_worker():
        Display.clear_display()
    
    thread = threading.Thread(target=clear_screen_worker)
    thread.start()

def playMusic(path):
    audio_command_queue.put(("play", path))
    print("Queued music for playback:", path)


def stopMusic():
    audio_command_queue.put(("stop", None))
    print("Queued stop music command")



def audio_thread():
    while True:
        command, path = audio_command_queue.get()
        if command == "play":
            speaker.play(path)
        elif command == "stop":
            speaker.stop_music()
        audio_command_queue.task_done()




def read_sensor_values():
    while True:
        #Read values
        #-- -- --
          
        #Afstandssensor
        # distance = AfstandSens.get_distance()
        # if distance is not None:
        #     print(f"Distance: {distance}cm")
        # else: 
        #     distance = 0
        #     print(f"Distance: {distance}cm")



        #Pressure sensors
        sens_Pressure_1 = MCPreader.read_channel(0)
        #print(f"MCP 0 - Pressure sens 1: {sens_Pressure_1}")
        sens_Pressure_2 = MCPreader.read_channel(1)
        #print(f"MCP 1 - Pressure sens 2: {sens_Pressure_2}")
        sens_Pressure_3 = MCPreader.read_channel(2)
        #print(f"MCP 2 - Pressure sens 3: {sens_Pressure_3}")
        if sens_Pressure_1 > 550:
            speaker.stop_music()
            print("Stopping audio")
        if sens_Pressure_2 > 550:
            playMusic(path_Oof)
            print("Playing OOF")
        if sens_Pressure_3 > 550:
            playMusic(path_Countdown)
            print("Playing countdown")
        
        time.sleep(0.2)




        #Joystick
        #sens_Joystick_Y = MCPreader.read_channel(3)
        #print(f"MCP 3 - Y value joystick: {sens_Joystick_Y}")
        #sens_Joystick_X = MCPreader.read_channel(4)
        #print(f"MCP 4 - X value joystick: {sens_Joystick_X}")
        #time.sleep(0.2)
    

def read_PunchMeter_values():
    while True:
        
        max_velocity_kmh, duration = punchMeter.measure_punch_speed()
        if max_velocity_kmh > 0:
            print(f"Velocity: {max_velocity_kmh}, time: {duration}")
            time.sleep(0.25)  # adjust the sleep time as necessary



try:    
    print("Code started running")
    speaker.connect(MAC_Bluetooh)
    display_image(path_MCT, 2)
    
    
    rfid_thread = threading.Thread(target=joystick_functions, daemon=True)
    read_sensor_thread = threading.Thread(target=read_sensor_values, daemon=True)
    punchMeter_thread = threading.Thread(target=read_PunchMeter_values, daemon=True)
    

    threading.Thread(target=audio_thread, daemon=True).start()
    rfid_thread.start()
    read_sensor_thread.start()
    punchMeter_thread.start()


    playMusic(path_Countdown)
    time.sleep(5)
    playMusic(path_song)
    while True:
        time.sleep(1)
        

        
      
        
    
    
   

except KeyboardInterrupt as e:
    print(e)

finally:
    print("Code stopped running")
    AfstandSens.cleanup()
    GPIO.cleanup()