#!/bin/bash

# Test script for iframe timeout functionality
set -e

echo "Starting iframe timeout test..."

# Start the daemon in background
echo "Starting cremotedaemon..."
./cremotedaemon --debug &
DAEMON_PID=$!

# Wait for daemon to start
sleep 2

# Function to cleanup
cleanup() {
    echo "Cleaning up..."
    kill $DAEMON_PID 2>/dev/null || true
    wait $DAEMON_PID 2>/dev/null || true
}

# Set trap for cleanup
trap cleanup EXIT

# Test 1: Basic iframe switching with timeout
echo "Test 1: Basic iframe switching with timeout"
TAB_ID=$(./cremote open-tab --timeout 5 | grep -o '"[^"]*"' | tr -d '"')
echo "Created tab: $TAB_ID"

# Load test page
./cremote load-url --tab "$TAB_ID" --url "file://$(pwd)/test-iframe.html" --timeout 10
echo "Loaded test page"

# Switch to iframe with timeout
echo "Switching to iframe with 5 second timeout..."
./cremote switch-iframe --tab "$TAB_ID" --selector "#test-iframe" --timeout 5
echo "Successfully switched to iframe"

# Try to click button in iframe
echo "Clicking button in iframe..."
./cremote click-element --tab "$TAB_ID" --selector "#iframe-button" --selection-timeout 5 --action-timeout 5
echo "Successfully clicked iframe button"

# Switch back to main
echo "Switching back to main context..."
./cremote switch-main --tab "$TAB_ID"
echo "Successfully switched back to main"

# Try to click main button
echo "Clicking main page button..."
./cremote click-element --tab "$TAB_ID" --selector "#main-button" --selection-timeout 5 --action-timeout 5
echo "Successfully clicked main button"

# Test 2: Test timeout with non-existent iframe
echo ""
echo "Test 2: Testing timeout with non-existent iframe"
set +e  # Allow command to fail
./cremote switch-iframe --tab "$TAB_ID" --selector "#non-existent-iframe" --timeout 2
RESULT=$?
set -e

if [ $RESULT -eq 0 ]; then
    echo "ERROR: Expected timeout failure but command succeeded"
    exit 1
else
    echo "SUCCESS: Timeout correctly handled for non-existent iframe"
fi

echo ""
echo "All iframe timeout tests passed!"
