import serial
import time
import re
#open the video
import os
os.system("open -a 'QuickTime Player' Haptics_video.mp4")
#start to play the video
os.system("osascript -e 'tell application \"QuickTime Player\" to play document 1'")


# Establish a serial connection (adjust the COM port and baud rate as needed)
ser = serial.Serial('/dev/tty.usbmodem101', 9600, timeout=1)

def send_command(command):
    """Send a command to the Arduino."""
    print(f"Sending command: {command}")
    ser.write(f"{command}\n".encode())

def timestamp_to_seconds(timestamp):
    """Convert timestamp string to seconds."""
    hours, minutes, seconds, milliseconds = map(int, re.split('[:,]', timestamp))
    return hours * 3600 + minutes * 60 + seconds + milliseconds / 1000

def process_file(file_path):
    """Process the subtitle file and trigger effects based on timestamps."""
    with open(file_path, 'r') as file:
        lines = file.readlines()

    current_time = time.time()  # Get the current time at the start of processing

    # Process each pair of lines (timestamp and effect)
    for i in range(0, len(lines), 2):
        timestamp_line = lines[i].strip()
        effect_line = lines[i+1].strip().lower().strip('[]')
        
        start_timestamp, end_timestamp = timestamp_line.split(' --> ')
        start_seconds = timestamp_to_seconds(start_timestamp)
        end_seconds = timestamp_to_seconds(end_timestamp)

        # Calculate target times based on the current time
        target_start_time = current_time + start_seconds
        target_end_time = current_time + end_seconds

        # Sleep until the start time
        time.sleep(max(0, target_start_time - time.time()))

        # Send start command
        send_command(f"START {effect_line}")

        # Sleep until the end time
        time.sleep(max(0, target_end_time - time.time()))

        # Send stop command
        send_command(f"STOP {effect_line}")

    ser.close()

# Adjust the file path as needed
process_file('processed_captions.srt')
