#!/usr/bin/env python3
"""
Test script for GSM simulator and UI together.
This script starts the GSM simulator in a separate process and launches the UI.
"""

import subprocess
import time
import sys
import os
import signal

def main():
    """Main function to run GSM simulator and UI together."""
    gsm_process = None
    ui_process = None
    
    try:
        print("Starting GSM and UI Test...")
        print("-" * 50)
        
        # Change to DryBox directory
        drybox_dir = os.path.join(os.path.dirname(__file__), 'DryBox')
        os.chdir(drybox_dir)
        
        # Start GSM simulator
        print("1. Starting GSM simulator...")
        gsm_process = subprocess.Popen(
            [sys.executable, 'gsm_simulator.py'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True
        )
        
        # Give the GSM simulator time to start
        time.sleep(2)
        
        # Check if GSM simulator started successfully
        if gsm_process.poll() is not None:
            stderr = gsm_process.stderr.read()
            print(f"ERROR: GSM simulator failed to start: {stderr}")
            return 1
        
        print("   GSM simulator started successfully on port 12345")
        
        # Start UI
        print("\n2. Starting Phone UI...")
        ui_process = subprocess.Popen(
            [sys.executable, 'UI/python_ui.py'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True
        )
        
        # Give the UI time to start
        time.sleep(2)
        
        # Check if UI started successfully
        if ui_process.poll() is not None:
            stderr = ui_process.stderr.read()
            print(f"ERROR: UI failed to start: {stderr}")
            return 1
        
        print("   UI started successfully")
        print("\n" + "=" * 50)
        print("GSM Simulator and UI are running!")
        print("=" * 50)
        print("\nInstructions:")
        print("- The UI shows two phones that can call each other")
        print("- Click 'Call' on Phone 1 to call Phone 2")
        print("- Phone 2 will show 'Incoming Call' - click 'Answer' to accept")
        print("- During the call, audio packets will be exchanged")
        print("- Click 'Hang Up' to end the call")
        print("\nPress Ctrl+C to stop the test...")
        
        # Wait for user interruption
        while True:
            time.sleep(1)
            
            # Check if processes are still running
            if gsm_process.poll() is not None:
                print("\nWARNING: GSM simulator has stopped!")
                break
            if ui_process.poll() is not None:
                print("\nINFO: UI has been closed by user")
                break
                
    except KeyboardInterrupt:
        print("\n\nStopping test...")
    except Exception as e:
        print(f"\nERROR: {e}")
        return 1
    finally:
        # Clean up processes
        if gsm_process and gsm_process.poll() is None:
            print("Stopping GSM simulator...")
            gsm_process.terminate()
            try:
                gsm_process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                gsm_process.kill()
                
        if ui_process and ui_process.poll() is None:
            print("Stopping UI...")
            ui_process.terminate()
            try:
                ui_process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                ui_process.kill()
                
        print("Test completed.")
    
    return 0

if __name__ == "__main__":
    sys.exit(main())