#!/usr/bin/env python3
#
# copyright @ zzir
#

import os.path

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.queues
import tornado.escape
import uimodule as md


from handlers import *
from admin.admin_handlers import *

from tornado.options import define, options
define("port", default=8080, help="run in port", type=int)
define("host", default="127.0.0.1", help="run in host", type=str)


# session setting
class Application(tornado.web.Application):
    def __init__(self):
        handlers = []
        settings = dict()
        session_settings = dict(
            driver="memory",
            driver_settings="{'host':self}",
            sid_name='msid',
            session_lifetime='1200',
            force_persistence='True',
        )
        settings.update(session_settings)
        tornado.web.Application.__init__(self, handlers=handlers, **settings)


def main():
    # handlers.update(dic)
    handlers = [
        (r"/", IndexHandler),
        (r"/page/(\d+)", IndexHandler),
        (r"/post/(.*)", PostHandler),
        (r"/about\/?", AboutHandler),
        (r"/reply", ReplyHandler),
        (r"/reply/(.*)", ReplyHandler),
        (r"/verificationcodeimg", ReplyVerificationCodeHandler),
        (r"/verificationcodeimg/(.*)", ReplyVerificationCodeHandler),
        (r"/archives?\/?", ArchiveHandlers),
        (r"/columns?\/?", ColumnHandlers),
        (r"/tags?\/?", TagHandlers),
        (r"/tag/(.*)", TagHandlers),

        (CONFIG['ADMIN_URL'], LoginHanlder),
        (r"/loginverificationcodeimg", LoginVerificationCodeHandler),
        (r"/loginverificationcodeimg/(.*)", LoginVerificationCodeHandler),
        (r'/login_out', LoginOutHanlder),
        (CONFIG['ADMIN_URL']+'/index', AdminIndexHandler),
        (CONFIG['ADMIN_URL'] + r'/index/(\d+)', AdminIndexHandler),
        (CONFIG['ADMIN_URL'] + r'/edit', EditIndexHandler),
        (CONFIG['ADMIN_URL'] + r'/edit/(\d+)', EditIndexHandler),
        (CONFIG['ADMIN_URL'] + r'/del/(\d+)', DelPostHandler),
        (CONFIG['ADMIN_URL'] + r'/reply', ReplyManegeHandler),
    ]
    settings = {
        'template_path': os.path.join(os.path.dirname(__file__), "templates"),
        'static_path': os.path.join(os.path.dirname(__file__), "static"),
        'cookie_secret': "e232a20ff9d977ac24307f7bb7a6ed3a875f5a32",
        'xsrf_cookies': 'True',
        'gzip': True,
        'ui_modules': md,
        'login_url': CONFIG['ADMIN_URL'],
        'debug': True   #提交删除此行
    }

    tornado.options.parse_command_line()    #接收命令行参数 --port=80
    app = tornado.web.Application(handlers, **settings)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port, options.host)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()
