# Path: elixir_models.py
# class User(BaseModel):
#     '''User contains details useful for authenticating a user for when they
#     initially log in.'''
# 
#     username = CharField(unique=True)
#     password = CharField()
#     email = CharField(null=True)
#     # Also has 'characters'
# 
#     def __repr__(self):
#         uname = self.username
#         s = "s"*(len(self.characters)-1)
#         chars = ', '.join([c.name for c in self.characters])
#         return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
# 
# class Character(BaseModel):
#     '''Character contains the details for characters that users may control.'''
# 
#     name = CharField(unique=True)
# 
#     speed = FloatField(default=1)
# 
#     user = ForeignKeyField(User, related_name='characters')
#     # Also has 'zones'
# 
# 
#     def __repr__(self):
#         return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
# 
# Path: settings.py
# CHARSERVERPORT = 1235
# 
# 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


import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
        self.write(json.dumps(self.get_zone(character)))
        self.set_header('Content-Type', 'application/json')

    def get_zone(self, charname):
        '''Queries the database for information pertaining directly
        to the character.
        It currently only returns the zone the character is in.'''
        return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}

    # TODO: Add character online/offline status

class CharacterCreationHandler(BaseHandler):
    '''CharacterHandler handles character creation.'''

    @tornado.web.authenticated
    def post(self):
        character_name = self.get_argument("character_name")
        character_name = self.create(character_name)
        if character_name is False:
            # Creating the character was prohibited.
            raise tornado.web.HTTPError(400, 'Character already exists.')
        elif not character_name:
            # Creating the character failed outright.
            raise tornado.web.HTTPError(400, 'Creating character failed.')

        self.write(character_name)

    def create(self, character_name):
        logging.info("Creating a character named %s" % character_name)
        try:

# Path: elixir_models.py
# class User(BaseModel):
#     '''User contains details useful for authenticating a user for when they
#     initially log in.'''
# 
#     username = CharField(unique=True)
#     password = CharField()
#     email = CharField(null=True)
#     # Also has 'characters'
# 
#     def __repr__(self):
#         uname = self.username
#         s = "s"*(len(self.characters)-1)
#         chars = ', '.join([c.name for c in self.characters])
#         return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
# 
# class Character(BaseModel):
#     '''Character contains the details for characters that users may control.'''
# 
#     name = CharField(unique=True)
# 
#     speed = FloatField(default=1)
# 
#     user = ForeignKeyField(User, related_name='characters')
#     # Also has 'zones'
# 
# 
#     def __repr__(self):
#         return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
# 
# Path: settings.py
# CHARSERVERPORT = 1235
# 
# 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: charserver.py
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler

        self.write(json.dumps(self.get_zone(character)))
        self.set_header('Content-Type', 'application/json')

    def get_zone(self, charname):
        '''Queries the database for information pertaining directly
        to the character.
        It currently only returns the zone the character is in.'''
        return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}

    # TODO: Add character online/offline status

class CharacterCreationHandler(BaseHandler):
    '''CharacterHandler handles character creation.'''

    @tornado.web.authenticated
    def post(self):
        character_name = self.get_argument("character_name")
        character_name = self.create(character_name)
        if character_name is False:
            # Creating the character was prohibited.
            raise tornado.web.HTTPError(400, 'Character already exists.')
        elif not character_name:
            # Creating the character failed outright.
            raise tornado.web.HTTPError(400, 'Creating character failed.')

        self.write(character_name)

    def create(self, character_name):
        logging.info("Creating a character named %s" % character_name)
        try:

            user = User.get(username=self.get_current_user())