import json

from tornado import httpserver
from tornado.ioloop import IOLoop
from tornado.options import define
from tornado.web import Application, RequestHandler

from server import db

define("port", default=3002, help="Default port for the WebServer")

class XMasRequestHandler(RequestHandler):
    def set_default_headers(self):
        origin = self.request.headers.get('Origin')
        if origin in ['http://localhost:3001', 'http://localhost', 'http://127.0.0.1', 'http://christmas.logicp.ca']:
            self.set_header("access-control-allow-origin", origin)
            self.set_header("Access-Control-Allow-Headers", "x-requested-with")
            self.set_header('Access-Control-Allow-Methods', 'GET, PUT, DELETE, OPTIONS')
            # HEADERS!
            self.set_header("Access-Control-Allow-Headers", "access-control-allow-origin,authorization,content-type")


class AttendeeHandler(XMasRequestHandler):
    def data_received(self, chunk):
        pass

    def options(self, *args, **kwargs):
        pass


    async def post(self, *args, **kwargs):
        print(self.request.body)
        data = json.loads(self.request.body.decode('utf-8'))
        result = await db.add_attendee(data['name'], data['guest'], data['cat'])
        self.write(json.dumps({'response': str(result), 'error': str(not result)}))


class ListHandler(XMasRequestHandler):
    async def get(self, *args, **kwags):
        attendees = await db.fetch_attendees()
        self.write(json.dumps({'attendees': [{'name': x.name, 'guest': x.guest, 'cat': x.cat} for x in attendees]}))


class ChristmasApplication(Application):
    def __init__(self):
        self.session = None

        handlers = [
            # Home
            (r"/list", ListHandler),

            # User GUI

            # - Profile
            (r"/attendee", AttendeeHandler),
        ]
        settings = {
            "debug": True,
            "cookie_secret": "ashda89sduaosihdsauDIOh",
        }

        Application.__init__(self, handlers, **settings)

if __name__ == "__main__":
    application = ChristmasApplication()
    http_server = httpserver.HTTPServer(application)
    http_server.listen(3002)
    db.Base.metadata.create_all(bind=db.engine)
    loop_instance = IOLoop.instance()
    loop_instance.start()