# encoding: utf-8
from __future__ import unicode_literals

import atexit
import gc
import os

import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.web

from intranet.webauth.lib import settings
from intranet.webauth.lib.auth_request_handler import AuthRequestHandler
from intranet.webauth.lib.check_oauth_token_handler import CheckOAuthTokenHandler
from intranet.webauth.lib.monitorings.cache_monitorings import (
    CheckCacheIntegrityHandler,
    CheckCacheFreshnessHandler,
    CheckRedisIntegrityHandler,
)
from intranet.webauth.lib.monitorings.qloud_sync_monitorings import CheckQloudSyncHandler
from intranet.webauth.lib.monitorings.unistat import Unistat
from intranet.webauth.lib.oauth_callback_handler import OAuthCallbackHandler
from intranet.webauth.lib.save_oauth_token_handler import SaveOAuthTokenHandler
from intranet.webauth.lib.utils import setup_logging, patch_cookies


setup_logging()
patch_cookies()


class GcHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        threshold = gc.get_threshold()
        self.set_status(200)
        self.finish(repr(threshold) + '\n')


class GcOnHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        gc.set_threshold(700, 10, 10)
        self.set_status(200)
        self.finish('enable\n')


class GcOffHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        gc.set_threshold(0)
        atexit.register(os._exit, 0)
        self.set_status(200)
        self.finish('disable\n')


class PingHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        self.set_status(200)
        self.finish('OK\n')


def make_app():
    handlers = [(r"/auth_request", AuthRequestHandler),
                (r"/check_oauth_token", CheckOAuthTokenHandler),
                (r"/oauth_callback", OAuthCallbackHandler),
                (r"/save_oauth_token", SaveOAuthTokenHandler),
                (r"/monitorings/check-cache-integrity", CheckCacheIntegrityHandler),
                (r"/monitorings/check-redis-integrity", CheckRedisIntegrityHandler),
                (r"/monitorings/check-cache-freshness", CheckCacheFreshnessHandler),
                (r"/monitorings/check-qloud-sync", CheckQloudSyncHandler),
                (r"/unistat", Unistat),
                (r"/gc", GcHandler),
                (r"/gc/on", GcOnHandler),
                (r"/gc/off", GcOffHandler),
                (r"/ping", PingHandler),
                ]

    return tornado.web.Application(handlers, serve_traceback=settings.WEBAUTH_DEBUG)


def main():
    app = make_app()
    server = tornado.httpserver.HTTPServer(app)
    server.bind(80)
    server.start(settings.WEBAUTH_TORNADO_WORKERS)
    tornado.ioloop.IOLoop.current().start()


if __name__ == '__main__':
    main()
