"""
Helper library for tornado
"""

import tornado.web
import tornado.gen

class CallbackHandler(tornado.web.RequestHandler):
    """
    Request handler class that exposes methods to make jsonp requests easier.
    """
    def write_with_callback(self, obj):
        """
        Write a response as a jsonp callback.
        """
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE')
        callback = self.get_argument('callback', None)
        if callback:
            obj = '{0}({1});'.format(callback, json.dumps(obj))
        self.write(obj)

    @tornado.gen.coroutine
    def options(self, *args, **kwargs):
        """
        Expose all methods in options.
        """
        self.set_header('Allow', 'GET,DELETE,PUT,POST,OPTIONS')
        self.write_with_callback('')
