import os
import json
import random
import logging
import urlparse
import webapp2

from google.appengine.api import channel
from google.appengine.ext import db
from google.appengine.ext.webapp import template


class Client(db.Model):
    username = db.StringProperty(required=True)
    token = db.StringProperty(required=False)


class MainPage(webapp2.RequestHandler):
    
    def get(self):
        default_username = 'john.doe' + str(random.randint(0, 1000))
        username = self.request.get('username', default_username)
        client = Client(username = username)
        db.put(client)
        client.token = channel.create_channel(str(client.key().id()))
        db.put(client)
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, {
            'token': client.token,
            'username': username
        }))
        
    def post(self):
        qs = urlparse.parse_qs(self.request.body)
        data = json.dumps({
            'message': qs['message'][0],
            'username': qs['username'][0]
        })
        for client in Client.all():
            client_id = str(client.key().id())
            logging.info('Sending data to {}...'.format(client_id))
            channel.send_message(client_id, data)


class ConnectedHandler(webapp2.RequestHandler):
    def post(self):
        client_id = self.request.get('from')
        logging.info("{} joined the party".format(client_id))


class DisconnectedHandler(webapp2.RequestHandler):
    def post(self):
        client_id = self.request.get('from')
        logging.info("Goodbye {}!".format(client_id))
        db.delete(Client.get_by_id(int(client_id)))


application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/_ah/channel/connected/', ConnectedHandler),
    ('/_ah/channel/disconnected/', DisconnectedHandler)
], debug=True)

