from flask_socketio import emit
from extensions import socketio, db
from models import Event, Inventory
from flask import request
import json
from dateutil import parser
from datetime import datetime

@socketio.on('connect')
def handle_connect():
    print('Client connected')
    emit('clear_events')
    
    # Send history
    try:
        recent_events = Event.query.order_by(Event.timestamp.desc()).limit(30).all()
        print(f"Sending history: {len(recent_events)} events")
        for event in reversed(recent_events):
            emit('game_event', event.to_dict())
    except Exception as e:
        print(f"Error sending history: {e}")

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

@socketio.on('game_event')
def handle_game_event(data):
    # data = {type: 'CHAT', player: 'Name', content: 'Message', ...}
    print(f"Received event: {data}")
    
    # Save to DB
    try:
        if not data.get('type'):
            print(f"Error: Missing event type in {data}")
            return

        event_timestamp = None
        if data.get('timestamp'):
            try:
                event_timestamp = parser.parse(data.get('timestamp'))
            except Exception as e:
                print(f"Error parsing timestamp: {e}")
                event_timestamp = datetime.utcnow()

        event = Event(
            event_type=data.get('type'),
            player_uuid=data.get('uuid'),
            player_name=data.get('player'),
            content=data.get('content'),
            location=data.get('location'),
            timestamp=event_timestamp or datetime.utcnow()
        )
        db.session.add(event)
        db.session.commit()
        print(f"Event saved to DB: {event.id}")

        # If inventory data is present, save it
        if 'inventory' in data:
            inventory = Inventory(
                event_id=event.id,
                player_uuid=data.get('uuid'),
                items=json.dumps(data.get('inventory'))
            )
            db.session.add(inventory)
            db.session.commit()
            print(f"Inventory saved for event {event.id}")
            
    except Exception as e:
        print(f"Error saving event to DB: {str(e)}")
        db.session.rollback()

    # Broadcast to admin dashboard
    print(f"Broadcasting event: {data}")
    emit('game_event', data, broadcast=True)

@socketio.on("*")
def handle_any_event(event, methods=None, data=None):
    if event not in ['connect', 'disconnect']:
        print(f"Server received event: {event} with data: {data}")
