from flask import Flask, escape, request, jsonify
from flask_cors import CORS, cross_origin
from urllib import parse
from functools import lru_cache
import requests

app = Flask(__name__)
cors = CORS(app)

JIRA_HOST = "xxx"
JIRA_USERNAME = "yyy"
JIRA_TOKEN = "jjj"


class JiraService:
    credentials = None

    @staticmethod
    def build_url(baseurl, path, args_dict):
        url_parts = list(parse.urlparse(baseurl))
        url_parts[2] = path
        url_parts[4] = parse.urlencode(args_dict)
        return parse.urlunparse(url_parts)

    @staticmethod
    @lru_cache(maxsize=5)
    def execute_jql(jql):
        url = JiraService.build_url(
            f'https://{JIRA_HOST}.atlassian.net/',
            '/rest/api/latest/search',
            {'jql': jql}
        )
        response = requests.get(
            url,
            auth=(JIRA_USERNAME, JIRA_TOKEN),
            headers={'Content-Type': 'application/json'}
        )

        return response.json()


@app.route('/jql')
@cross_origin()
def hello():
    jql = request.args.get("query", "")
    no_cache = request.args.get('noCache', False)

    if no_cache != False:
        JiraService.execute_jql.cache_clear()

    if len(jql) > 0:
        data = JiraService.execute_jql(jql)
        return jsonify(data)
    return jsonify({'message': 'Please, specify query param'}), 400


if __name__ == '__main__':
    app.run()