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

__author__ = 'ghost'

import tornado.web
import tornado.httpserver
import tornado.ioloop
import session

REDIS_CONF = {
    'host': 'localhost',
    'port': 6379,
    'password': '',
    'db': 7
}

SETTINGS = {
    "debug": True,
    "cookie_secret": "YXRvbS50cmFkZSBpcyB0aGUgYmVzdAo=",
}


def login_require(method):
    def wrapper(self, *args, **kwargs):
        userid = self.current_user
        if userid:
            return method(self, *args, **kwargs)
        else:
            self.write("no login")
            self.finish()
    return wrapper


class BaseHandler(tornado.web.RequestHandler):

    def initialize(self):
        self.session = session.Session(self.application.session_manager, self)

    def get_current_user(self):
        super(BaseHandler, self).get_current_user()
        userid = self.session.get('login')
        if not userid:
            return None
        return userid


class IndexHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.write("index")


class LoginHandler(BaseHandler):

    def get(self, *args, **kwargs):
        self.session['login'] = 'rsj217'
        self.session.save()
        self.write('login success')


class LogoutHandler(BaseHandler):

    def get(self, *args, **kwargs):
        if self.session.get('login'):
            self.session.pop('login')
            self.session.save()
            return self.finish('logout')
        self.finish('you have not login')


class UserHandler(BaseHandler):

    @login_require
    def get(self, *args, **kwargs):
        self.write('user')


class Application(tornado.web.Application):
    def __init__(self):
        super(Application, self).__init__(
            handlers=[
                (r'/', IndexHandler),
                (r'/user', UserHandler),
                (r'/login', LoginHandler),
                (r'/logout', LogoutHandler),
            ],
            **SETTINGS
        )

        self.session_manager = session.SessionManager("session_secret", REDIS_CONF, 3600)


if __name__ == '__main__':
    app = Application()
    server = tornado.httpserver.HTTPServer(app)
    server.listen(8000)
    tornado.ioloop.IOLoop.instance().start()
