import os
import logging
import threading
import time
import requests
import subprocess
from rtsparty import Stream
from objectdaddy import Daddy
from playsound import playsound
import random
import time

class HalloweenMannequinHead():

    def __init__(self):
        logging.info('Starting application')
        self._setup_stream()
        self._setup_object_recognition()


    def _setup_servo(self):
        """Sets up the servo; requires raspberry pi to run"""
        from servo_controller import ServoController
        self.servo_controller = ServoController()

    def _setup_stream(self):
        """Set up the stream to the camera"""
        logging.info('Starting stream')
        self.stream = Stream(os.environ.get('STREAM_URI', None))

    def _setup_object_recognition(self):
        """Set up object recognition and load models"""
        logging.info('Loading ML models')
        self.daddy = Daddy()

    def person_detected_play_audio(self, detection):
        list_of_sounds = ["1beholdTheCaveOfCarbano","2whatBehindTheRabbit", "3thatsTheMostFoul", "4iSoiledMyArmor","5thatRabbitHasAViscoius", "6ohItsJustAHarmlessLittleBunnny", "7runAway", "8howManyDidWeLose", "9weBetterNotRiskAnotherFrontal", "10weHaveTheHolyHand", "11andTheLordDidGrin", "12countToThree", "13lobTheHolyHand", "14onTwoFive"]
        random_index = random.randint(0,len(list_of_sounds)-1)
        sound_to_play = f"/Users/jarredparrett/Desktop/HalloweenAudio/{list_of_sounds[random_index]}.mp3"
        playsound(sound_to_play)
        time.sleep(10)

    def process_frames_from_stream(self):
        """Processes the frames from the stream"""
        while True:
            frame = self.stream.get_frame()
            if self.stream.is_frame_empty(frame):
                continue
            self.latest_frame = frame
            results, frame = self.daddy.process_frame(frame)
            for detection in results:
                if detection.is_person():
                    self.person_detected_play_audio(detection)


    def run(self):
        """Run the application"""
        try:
            self.process_frames_from_stream()
        except KeyboardInterrupt:
            logging.info('Exiting application')


if __name__ == '__main__':
    os.environ["STREAM_URI"] = "rtsp://jarred:<pass>@192.168.1.173/live"
    logging.basicConfig()
    logging.getLogger().setLevel(logging.INFO)
    hmh = HalloweenMannequinHead()
    hmh.run()
