#!/usr/bin/env python3
"""
Context Manager Example - Using Tunnel with context manager
Tunnel automatically closes when exiting the block
"""

from suxitunnel import Tunnel
import http.server
import socketserver
import threading
import time

def start_simple_server(port):
    """Start a simple HTTP server"""
    Handler = http.server.SimpleHTTPRequestHandler
    with socketserver.TCPServer(("", port), Handler) as httpd:
        httpd.serve_forever()

def example_basic_context_manager():
    """Basic usage with context manager"""
    PORT = 8000
    
    # Start server in background
    server_thread = threading.Thread(
        target=start_simple_server, 
        args=(PORT,), 
        daemon=True
    )
    server_thread.start()
    
    print("Example 1: Basic context manager usage\n")
    
    # Tunnel automatically closes when exiting
    with Tunnel(PORT) as tunnel:
        print(f"✅ Tunnel created: {tunnel.url}")
        print("Tunnel is active inside this block...")
        time.sleep(3)
        print("Exiting context manager...")
    
    print("✅ Tunnel automatically closed!\n")

def example_exception_handling():
    """Context manager handles exceptions gracefully"""
    PORT = 8001
    
    server_thread = threading.Thread(
        target=start_simple_server, 
        args=(PORT,), 
        daemon=True
    )
    server_thread.start()
    
    print("Example 2: Exception handling\n")
    
    try:
        with Tunnel(PORT) as tunnel:
            print(f"✅ Tunnel created: {tunnel.url}")
            print("Simulating an error...")
            raise ValueError("Something went wrong!")
    except ValueError as e:
        print(f"Caught exception: {e}")
    
    print("✅ Tunnel was still closed despite the exception!\n")

def example_multiple_operations():
    """Using tunnel for temporary operations"""
    PORT = 8002
    
    server_thread = threading.Thread(
        target=start_simple_server, 
        args=(PORT,), 
        daemon=True
    )
    server_thread.start()
    
    print("Example 3: Multiple operations\n")
    
    with Tunnel(PORT) as tunnel:
        print(f"✅ Tunnel: {tunnel.url}")
        
        # Do multiple operations
        operations = ["Operation 1", "Operation 2", "Operation 3"]
        for op in operations:
            print(f"  Executing {op}...")
            time.sleep(1)
        
        print("All operations complete!")
    
    print("✅ Tunnel closed after all operations\n")

if __name__ == "__main__":
    print("="*60)
    print("Context Manager Examples")
    print("="*60 + "\n")
    
    example_basic_context_manager()
    time.sleep(1)
    
    example_exception_handling()
    time.sleep(1)
    
    example_multiple_operations()
    
    print("="*60)
    print("All examples completed!")
    print("="*60)
