'''
Proxy server for getting hyperthesis annotation
'''
import os

import bottle
import requests
from bottle import route, response

app = application = bottle.Bottle()

config_file_path = os.getenv('CONFIG_PATH', "hypothesis_proxy.conf")

app.config.load_config(config_file_path)

# From https://stackoverflow.com/a/17262900
class EnableCors(object):
    name = 'enable_cors'
    api = 2

    def apply(self, fn, context):
        def _enable_cors(*args, **kwargs):
            # set CORS headers
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

            if bottle.request.method != 'OPTIONS':
                # actual request; reply with the actual response
                return fn(*args, **kwargs)

        return _enable_cors

app.install(EnableCors())

@app.route('/annotations')
def query_hypothesis():
    '''
    query hypothesis
    '''

    annotations_json = app.config.get('proxy.annotations_json', None)

    if annotations_json and os.path.isfile(annotations_json):
        import json
        with open(annotations_json, 'r') as f:
            return json.load(f)

    url = app.config.get('proxy.url', 'https://h.projet-episteme.org/api/search')
    headers = {}
    token = app.config.get('proxy.token')
    if token is not None:
        headers["Authorization"] = "Bearer " + token

    params = {}
    for config_tag in ['group', 'user', 'tag', 'limit']:
        config_val = app.config.get('proxy.%s' % config_tag)
        if config_val is not None:
            params[config_tag] = config_val

    offset = 0
    total = -1

    rows = []

    while total < 0 or offset < total:
        #TODO: handle errors
        res = requests.get(url, params=params, headers=headers)
        res_json = res.json()
        total = int(res_json['total'])
        rows += res_json['rows']
        offset = len(rows)
        params['offset'] = offset

    return {
        'rows': rows,
        'total': len(rows)
    }


if __name__ == "__main__":
    app.run(
        host=app.config.get('proxy.host', '127.0.0.1'),
        port=int(app.config.get('proxy.port', 8888))
    )
