#!/usr/bin/env python
#!-*- coding: utf-8 -*-

import os
import json

import tornado.web
import tornado.ioloop
import tornado.websocket
import tornado.auth

from tornado import template
from tornado.escape import linkify

import pymongo

from urlparse import urlsplit


#MONGO_URL = os.environ.get('MONGOHQ_URL')
MONGO_URL = os.getenv('MONGOHQ_URL', 'mongodb://localhost:27017/testdb')

class  MainHandler(tornado.web.RequestHandler):
    def get(self):
        db = self.application.db
        self.render('index.html')
        
class GoogleHandler(tornado.web.RequestHandler, tornado.auth.GoogleMixin):      
    def get(self):
        
        if self.get_argument("openid.mode", None):                  
            self.set_secure_cookie("user", self.get_argument("openid.ext1.value.firstname"))
            self.redirect('chat')
            return        
        self.authenticate_redirect()
        
        # Save the user with, e.g., set_secure_cookie()
    
    
class ChatHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")
    
    def get(self): 
        db = self.application.db
        messages = db.chat.find()
        #tabs = ["tab1","tab2","tab3"]
        self.render('chat/chat.html',messages=messages,user_name = self.get_current_user())

class WebSocket(tornado.websocket.WebSocketHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")
    
    def open(self):
        self.application.webSocketsPool.append(self)

    def on_message(self, message):
        
        db = self.application.db
        message_dict = json.loads(message);
        db.chat.insert(message_dict)
        
        for key, value in enumerate(self.application.webSocketsPool):
            if value != self:
                value.ws_connection.write_message(message)

    def on_close(self, message=None):
        for key, value in enumerate(self.application.webSocketsPool):
            if value == self:
                del self.application.webSocketsPool[key]

class Application(tornado.web.Application):
    def __init__(self):
        self.webSocketsPool = []

        settings = {
            'static_url_prefix': '/static/',
        }
        
        #self.db = connection.chat


        parsed = urlsplit(MONGO_URL)
        db_name = parsed.path[1:]

        # Get your DB
        self.db = pymongo.Connection(MONGO_URL)[db_name]

        # Authenticate
        if '@' in MONGO_URL:
            user, password = parsed.netloc.split('@')[0].split(':')
            self.db.authenticate(user, password)
        
        settings = {
            "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__"
        }

        #"login_url": "/login",
        
        handlers = (
            
            (r'/', MainHandler),
            (r'/auth', GoogleHandler),
            (r'/chat',ChatHandler),
            (r'/websocket/?', WebSocket),
            (r'/static/(.*)', tornado.web.StaticFileHandler,
            {'path': 'static/'})
        
         
        )

        tornado.web.Application.__init__(self, handlers,**settings)

application = Application()


if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()

