# Path: baseserver.py
# class BaseServer(Application):
#     def __init__(self, extra_handlers):
#         '''Expects a list of tuple handlers like:
#                 [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
#         '''
#         url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
# 
#         app_settings = {
#                 "cookie_secret": settings.COOKIE_SECRET,
#                 "login_url": ''.join((url, "/login")),
#                 }
# 
#         handlers = []
#         handlers.append((r"/version", VersionHandler))
#         handlers.append((r"/source", SelfServe))
#         handlers.append((r"/ping", PingHandler))
#         handlers.append((r"/", PingHandler))
# 
#         handlers.extend(extra_handlers)
# 
#         options.parse_command_line()
#         dburi = options.dburi
# 
#         # Connect to the elixir db
#         setup(db_uri=dburi)
# 
#         Application.__init__(self, handlers, debug=True, **app_settings)
# 
#     def start(self):
#         IOLoop.current().start()
# 
# class SimpleHandler(BaseHandler):
#     def __init__(self, output, *args):
#         self.output = output
#         RequestHandler.__init__(self, *args)
# 
#     def get(self):
#         self.write(self.output)
# 
# class BaseHandler(RequestHandler):
#     def _handle_request_exception(self, e):
#         if client:
#             client.captureException()
#         RequestHandler._handle_request_exception(self, e)
# 
#     def get_login_url(self):
#         return u"/login"
# 
#     def get_current_user(self):
#         user_json = self.get_secure_cookie("user")
#         if user_json:
#             return user_json
#         else:
#             return None
# 
#     def HTTPError(self, code, message):
#         def write_error(status_code, **kwargs):
#             self.write(message)
#         self.write_error = write_error
#         self.send_error(code)
#         self.write_error = old_write_error
# 
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
#     class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
#     def default(self, obj):
#     def exists(cls, *args, **kwargs):
#     def json_dumps(self):
#     def __repr__(self):
#     def __repr__(self):
#     def loc(self):
#     def loc(self, val):
#     def set_modified(self, date_time=None):
#     def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):


import json
import logging
import tornado
import settings
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Character, User, db
        :status 200: Successfully logged out.
    '''
    def get(self):
        self.clear_cookie("user")


class CharacterHandler(BaseHandler):
    '''CharacterHandler gets a list of characters for the given user account.
            GET /characters'''

    @tornado.web.authenticated
    def get(self):
        self.write(json.dumps(self.get_characters(self.get_current_user())))
        self.set_header('Content-Type', 'application/json')

    def get_characters(self, username):
        '''Queries the database for all characters owned by a particular user.'''
        user = User.get(username=username)
        logging.info(user.characters)
        return [c.name for c in user.characters]


if __name__ == "__main__":
    handlers = []
    handlers.append((r"/", lambda x, y: SimpleHandler(__doc__, x, y)))
    handlers.append((r"/register", RegistrationHandler))
    handlers.append((r"/login", AuthHandler))
    handlers.append((r"/logout", LogoutHandler))
    handlers.append((r"/characters", CharacterHandler))


# Path: baseserver.py
# class BaseServer(Application):
#     def __init__(self, extra_handlers):
#         '''Expects a list of tuple handlers like:
#                 [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
#         '''
#         url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
# 
#         app_settings = {
#                 "cookie_secret": settings.COOKIE_SECRET,
#                 "login_url": ''.join((url, "/login")),
#                 }
# 
#         handlers = []
#         handlers.append((r"/version", VersionHandler))
#         handlers.append((r"/source", SelfServe))
#         handlers.append((r"/ping", PingHandler))
#         handlers.append((r"/", PingHandler))
# 
#         handlers.extend(extra_handlers)
# 
#         options.parse_command_line()
#         dburi = options.dburi
# 
#         # Connect to the elixir db
#         setup(db_uri=dburi)
# 
#         Application.__init__(self, handlers, debug=True, **app_settings)
# 
#     def start(self):
#         IOLoop.current().start()
# 
# class SimpleHandler(BaseHandler):
#     def __init__(self, output, *args):
#         self.output = output
#         RequestHandler.__init__(self, *args)
# 
#     def get(self):
#         self.write(self.output)
# 
# class BaseHandler(RequestHandler):
#     def _handle_request_exception(self, e):
#         if client:
#             client.captureException()
#         RequestHandler._handle_request_exception(self, e)
# 
#     def get_login_url(self):
#         return u"/login"
# 
#     def get_current_user(self):
#         user_json = self.get_secure_cookie("user")
#         if user_json:
#             return user_json
#         else:
#             return None
# 
#     def HTTPError(self, code, message):
#         def write_error(status_code, **kwargs):
#             self.write(message)
#         self.write_error = write_error
#         self.send_error(code)
#         self.write_error = old_write_error
# 
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
#     class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
#     def default(self, obj):
#     def exists(cls, *args, **kwargs):
#     def json_dumps(self):
#     def __repr__(self):
#     def __repr__(self):
#     def loc(self):
#     def loc(self, val):
#     def set_modified(self, date_time=None):
#     def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):


# Path: authserver.py
import json
import logging
import tornado
import settings
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Character, User, db

        :status 200: Successfully logged out.
    '''
    def get(self):
        self.clear_cookie("user")


class CharacterHandler(BaseHandler):
    '''CharacterHandler gets a list of characters for the given user account.
            GET /characters'''

    @tornado.web.authenticated
    def get(self):
        self.write(json.dumps(self.get_characters(self.get_current_user())))
        self.set_header('Content-Type', 'application/json')

    def get_characters(self, username):
        '''Queries the database for all characters owned by a particular user.'''
        user = User.get(username=username)
        logging.info(user.characters)
        return [c.name for c in user.characters]


if __name__ == "__main__":
    handlers = []
    handlers.append((r"/", lambda x, y: SimpleHandler(__doc__, x, y)))
    handlers.append((r"/register", RegistrationHandler))
    handlers.append((r"/login", AuthHandler))
    handlers.append((r"/logout", LogoutHandler))
    handlers.append((r"/characters", CharacterHandler))


    server = BaseServer(handlers)