import RPi.GPIO as GPIO
import time
import subprocess
import logging
import os
import io
import soundfile as sf
import sounddevice as sd
import pygame
pygame.mixer.init()

# Setup logging
logging.basicConfig(filename='/home/pi/script_log.txt', level=logging.INFO, format='%(asctime)s - %(message)s')

# Setup GPIO pins
GPIO.setmode(GPIO.BCM)
button1_pin = 17  # GPIO pin for Button 1
button2_pin = 27  # GPIO pin for Button 2
led_pin = 22      # GPIO pin for LED
GPIO.setup(button1_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(button2_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.output(led_pin, GPIO.LOW)  # Turn off LED initially

# Global process variable
current_process = None
pygame.mixer.music.load('Welcome.mp3')
pygame.mixer.music.play()

def run_script(script_path):
    global current_process
    if current_process is not None:
        logging.info("Terminating existing process...")
        current_process.terminate()
        time.sleep(2)  # Give it some time to terminate
        if current_process.poll() is None:  # If it's still running
            logging.info("Force killing process...")
            current_process.kill()
        current_process.wait()
        current_process = None
        GPIO.output(led_pin, GPIO.LOW)  # Turn off LED

    logging.info(f"Starting {script_path}")
    current_process = subprocess.Popen(['python3', script_path])
    GPIO.output(led_pin, GPIO.HIGH)  # Turn on LED

try:
    while True:
        button1_state = GPIO.input(button1_pin)
        button2_state = GPIO.input(button2_pin)

        if button1_state == GPIO.LOW:  # Button 1 pressed
            run_script('/home/pi/Desktop/MasterFiles/Theproject/Labtourmode.py')
            pygame.mixer.music.load('mode1.mp3')
            pygame.mixer.music.play()
            time.sleep(0.5)  # Debounce delay

        if button2_state == GPIO.LOW:  # Button 2 pressed
            run_script('/home/pi/Desktop/MasterFiles/Theproject/generalnew.py')
            pygame.mixer.music.load('mode2.mp3')
            pygame.mixer.music.play()
            time.sleep(0.5)  # Debounce delay

        time.sleep(0.1)  # Small delay to debounce the buttons

finally:
    # Cleanup GPIO pins on exit
    if current_process is not None:
        current_process.terminate()
    GPIO.cleanup()
    logging.info("Button manager script terminated.")
