import RPi.GPIO as GPIO
import subprocess
import time
import random
import os

# Set up GPIO for PIR sensor
PIR_PIN = 21  # Change this to the desired GPIO pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN)

# Define the path to your video directory
video_dir = "YourPathtoVideos"

# List all the video files in the specified directory
video_files = [f for f in os.listdir(video_dir) if f.endswith(".mp4")]

# Initialize a timer for retriggering
retrigger_delay = 60  # Delay in seconds (set to 60 seconds for a 1-minute delay)
last_trigger_time = 0

# Function to play video with mpv
def play_video(video_path):
    mpv_command = f"mpv --fs {video_path}"
    subprocess.Popen(mpv_command, shell=True)

try:
    while True:
        if GPIO.input(PIR_PIN):
            current_time = time.time()
            if current_time - last_trigger_time >= retrigger_delay:
                print("Motion detected!")
                # Select a random video from the list
                random_video = random.choice(video_files)
                video_path = os.path.join(video_dir, random_video)

                # Play the selected video with mpv
                play_video(video_path)
                
                last_trigger_time = current_time  # Update the trigger time
                
                while GPIO.input(PIR_PIN):
                    time.sleep(1)  # Wait until motion stops

except KeyboardInterrupt:
    print("Exiting...")
finally:
    GPIO.cleanup()
