import numpy as np
import threading
import time
import subprocess
import os
from azure_connection import upload_to_azure_with_signed_url
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from datetime import datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import signal
from ext_api_func import *
from json_evaluation import json_report

# Global variable to manage recording process
#recording_process = None
recording = False
frames = []
stream = None
p = None

# Function to recheck the roster text periodically
def recheck_roster_text(driver, roster_xpath):
    while True:
        time.sleep(60)  # Wait for 5 minutes
        print("Rechecking roster text...")
        try:
            roster_text = driver.find_element(By.XPATH, roster_xpath).text
            print(f"Rechecked roster text: {roster_text}")

            # Check for "In this meeting (1)"
            if roster_text == "In this meeting (1)":
                print("No member in the meeting.")
                leave_button_xpath = '//*[@id="hangup-button"]/button'
                driver.find_element(By.XPATH, leave_button_xpath).click()
                print("'Leave' button clicked")
                break
        except Exception as e:
            print(f"Error while rechecking roster text: {e}")
            break

# # Function to start audio recording
# Global variable to track the ffmpeg process
ffmpeg_process = None

def start_recording(output_file):
    """
    Start recording audio using ffmpeg.
    
    Args:
    - output_file (str): Path to save the output WAV file.
    """
    global ffmpeg_process
    try:
        print(f"Starting audio recording... Output file: {output_file}")
        # Start the ffmpeg process
        ffmpeg_process = subprocess.Popen(
            ["ffmpeg", "-f", "pulse", "-i", "auto_null.monitor", output_file],
            stdout=subprocess.DEVNULL,  # Suppress stdout
            stderr=subprocess.STDOUT  # Suppress stderr
        )
    except Exception as e:
        print(f"Error starting ffmpeg process: {e}")

def stop_recording():
    """
    Stop the ffmpeg recording process.
    """
    global ffmpeg_process
    if ffmpeg_process:
        print("Stopping audio recording...")
        try:
            # Send SIGINT (CTRL+C) to stop the process gracefully
            ffmpeg_process.send_signal(signal.SIGINT)
            ffmpeg_process.wait()  # Wait for the process to terminate
            print("Recording stopped successfully.")
        except Exception as e:
            print(f"Error stopping ffmpeg process: {e}")
        finally:
            ffmpeg_process = None
    else:
        print("No recording process found to stop.")

# Function to automate the process of joining a meeting and recording
def automate_meeting(meeting_link, uniqueId, input_time, input_date, interview_id, node_url):
    print("Waiting for the scheduled time...")
    while True:
        current_time = datetime.now().strftime("%H:%M")
        current_date = datetime.now().strftime("%Y-%m-%d")

        if input_time == current_time and input_date == current_date:
            break
        time.sleep(1)  # Check every second
    print("Scheduled time reached. Starting process...")

    # Set up ChromeDriver using Service with headless options
    try:
        options = Options()
        options.add_argument("--headless")  # Run Chrome in headless mode
        options.add_argument("--no-sandbox")  # Necessary for certain Linux environments
        options.add_argument("--disable-dev-shm-usage")  # Fixes some Docker issues
        options.add_argument("--disable-gpu")  # Disables GPU hardware acceleration

        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=options)
    except Exception as e:
        print(f"Error initializing ChromeDriver: {e}")
        return

    # Output file for the audio recording
    output_audio_file = uniqueId + ".mp3"
    print("Output file assigned:", output_audio_file)

    try:
        print("Navigating to the Teams meeting link...")
        driver.get(meeting_link)

        # Wait until the name input field is visible and interactable
        print("Waiting for the name input field...")
        name_input_xpath = '//*[@id="app"]/div/div/div/div[5]/div/div/div/div[2]/div/div/div[2]/div[1]/div/div/div[2]/div[2]/span/input'
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, name_input_xpath)))

        # Automatically enter the name 'bot' into the input field
        driver.find_element(By.XPATH, name_input_xpath).send_keys('bot')
        print("Entered name: bot")

        # Automatically click the Join button
        time.sleep(5)
        join_button_xpath = '//*[@id="prejoin-join-button"]'
        driver.find_element(By.XPATH, join_button_xpath).click()
        print("Join button clicked")

        start_recording(output_audio_file)

        print(f"Recording started, saving to {output_audio_file}")

        # Wait for the meeting interface to fully load
        time.sleep(10)

        # Click on the "People" button
        print("Clicking the 'People' button...")
        people_button_xpath = '//*[@id="roster-button"]'
        driver.find_element(By.XPATH, people_button_xpath).click()
        print("'People' button clicked")

        # Extract and print the value at the specified XPath
        print("Extracting value from roster title section...")
        roster_xpath = '//*[@id="roster-title-section-2"]/span'
        WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, roster_xpath)))
        roster_text = driver.find_element(By.XPATH, roster_xpath).text
        print("-------------------------------------------------")
        print(f"Value in roster title section: {roster_text}")


        # Start a thread to recheck roster text every 5 minutes
        recheck_roster_text(driver,roster_xpath,)

    finally:
        # Stop the audio recording
        stop_recording()

        # Stop the browser after a delay
        time.sleep(10)
        driver.quit()
        print("Browser closed.")

        # Upload the recording to Azure and return the URL
        ai_url = "https://hw-aireport.foobar.in/json_report"
        blob_url = upload_to_azure_with_signed_url(output_audio_file, output_audio_file)
        json_data = json_report(output_audio_file, ai_url, blob_url)
        response = send_interview_report(node_url, interview_id, blob_url, json_data)
        print("Node Api response:", response)



