import datetime
import json
import thread
import time
import uuid
from Queue import Queue
from datetime import datetime

from flask import Flask, render_template, request, session, Response, \
    stream_with_context

app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdf'
app.debug = True
heartbeat_interval = 10 # seconds

class ExtensibleJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'to_JSON'):
            return obj.to_JSON()
        return super(ExtensibleJSONEncoder, self).default(obj)

def jsonify(*args, **kwargs):
    indent = None
    status = kwargs.pop('_status', 200)
    mime = kwargs.pop('_mime', 'application/json')
    data = args[0] if args else dict(kwargs)

    if app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
       and not request.is_xhr:
        indent = 2

    dump = json.dumps(data, indent=indent)
    return app.response_class(dump, status=status, mimetype=mime)



# Override Flask's json encoder to check for to_JSON method on objects
app.json_encoder = ExtensibleJSONEncoder

class WebRTCUser(object):
    id = None
    username = None
    connected_at = None
    namespace = None

    def __init__(self, id, username=None):
        self.id = id
        self.username = username
        self.connected_at = datetime.utcnow()
        self.rooms = []
        self.messages = Queue()

    def __repr__(self):
        return '<WebRTCUser %s %s>' % (self.id, self.username)

    def add_stream(self, stream_id):
        self.streams[stream_id] = dict(queue=Queue())

    def emit(self, event=None, **data):
        if event:
            data['event'] = event
        payload = data.pop('_payload', None)
        if not payload:
            payload = json.dumps(data)
        if payload != '{"event": "heartbeat"}':
            print 'Emitting %s to %s' % (payload, self)
        self.messages.put_nowait(payload)

    def emit_to_rooms(self, event, **data):
        for room in self.rooms:
            room.emit(event, **data)

    def to_JSON(self):
        return dict(
            id=self.id,
            username=self.username
        )

class WebRTCRoom(object):