"""
OMNIWEB Real-time Chat Example - WebSockets + Broadcasting
"""

from omniweb import OmniWeb, HTMLResponse
from omniweb.realtime import enable_realtime, broadcast
import secrets

app = OmniWeb(title="Real-time Chat", debug=True)

# Enable real-time features
realtime = enable_realtime(app)

# Store active connections
active_users = {}


@app.get("/")
async def home():
    """Serve chat UI."""
    html = """
<!DOCTYPE html>
<html>
<head>
    <title>OMNIWEB Real-time Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .chat-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        h1 { color: #667eea; margin: 0 0 20px 0; }
        #messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            background: #f9f9f9;
        }
        .message {
            padding: 8px;
            margin: 5px 0;
            border-radius: 5px;
            background: #e3f2fd;
        }
        .message.own {
            background: #c8e6c9;
            text-align: right;
        }
        .message.system {
            background: #fff3cd;
            font-style: italic;
            text-align: center;
        }
        .input-group {
            display: flex;
            gap: 10px;
        }
        input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        button {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
        }
        button:hover {
            background: #5568d3;
        }
        .status {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            background: #d4edda;
            color: #155724;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>💬 OMNIWEB Real-time Chat</h1>
        <div class="status" id="status">Connecting...</div>
        <div id="messages"></div>
        <div class="input-group">
            <input type="text" id="messageInput" placeholder="Type your message...">
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script>
        const ws = new WebSocket('ws://localhost:8000/ws');
        const messagesDiv = document.getElementById('messages');
        const messageInput = document.getElementById('messageInput');
        const statusDiv = document.getElementById('status');
        
        const username = 'User_' + Math.random().toString(36).substr(2, 5);

        ws.onopen = () => {
            statusDiv.textContent = '✅ Connected as ' + username;
            statusDiv.style.background = '#d4edda';
        };

        ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            addMessage(data);
        };

        ws.onclose = () => {
            statusDiv.textContent = '❌ Disconnected';
            statusDiv.style.background = '#f8d7da';
        };

        function addMessage(data) {
            const div = document.createElement('div');
            div.className = 'message';
            
            if (data.event === 'system') {
                div.className += ' system';
                div.textContent = data.data.message;
            } else {
                if (data.data.username === username) {
                    div.className += ' own';
                }
                div.textContent = `${data.data.username}: ${data.data.message}`;
            }
            
            messagesDiv.appendChild(div);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function sendMessage() {
            const message = messageInput.value.trim();
            if (message) {
                ws.send(JSON.stringify({
                    event: 'message',
                    data: {
                        username: username,
                        message: message
                    }
                }));
                messageInput.value = '';
            }
        }

        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>
    """
    return HTMLResponse(html)


@app.websocket("/ws")
async def websocket_endpoint(websocket):
    """WebSocket endpoint for chat."""
    await websocket.accept()
    
    # Generate client ID
    client_id = secrets.token_urlsafe(8)
    conn = realtime.add_connection(client_id, websocket)
    
    # Join chat room
    realtime.join_room(client_id, "chat")
    
    # Announce join
    await broadcast(
        "system",
        {"message": f"🎉 New user joined! ({len(realtime.rooms.get('chat', []))} online)"},
        room="chat"
    )
    
    try:
        while True:
            # Receive message
            data = await conn.receive_json()
            
            # Broadcast to all in room
            await broadcast(
                data.get("event", "message"),
                data.get("data", {}),
                room="chat"
            )
    
    except Exception as e:
        print(f"WebSocket error: {e}")
    
    finally:
        # Clean up
        realtime.remove_connection(client_id)
        
        # Announce leave
        await broadcast(
            "system",
            {"message": f"👋 User left ({len(realtime.rooms.get('chat', []))} online)"},
            room="chat"
        )


@app.get("/stats")
async def chat_stats():
    """Get chat statistics."""
    return realtime.get_stats()


if __name__ == "__main__":
    print("""
╔════════════════════════════════════════╗
║  💬 OMNIWEB Real-time Chat            ║
╚════════════════════════════════════════╝

Features:
  ✅ WebSocket connections
  ✅ Real-time broadcasting
  ✅ Rooms/Channels
  ✅ User presence
  ✅ Connection management

Open in browser:
  http://localhost:8000

Open multiple tabs to see real-time chat!

Starting server...
    """)
    
    app.run(host="127.0.0.1", port=8000, reload=True)
