import json

from flask import Flask, request

from analysis_client import get_analysis_client
from translator_client import get_translation

app = Flask(__name__)

analysis_client = None
translator_client = None


def serialize_linked_entities(linked_entities):
    result = []
    for entity in linked_entities:
        entity_item = {}
        for key in ['bing_entity_search_api_id', 'data_source', 'data_source_entity_id', 'language', 'name', 'url']:
            if key in entity:
                entity_item[key] = entity[key]
        if 'matches' in entity:
            matches_list = []
            for match in entity['matches']:
                match_item = {}
                for key in ['confidence_score', 'length', 'offset', 'text']:
                    if key in match:
                        match_item[key] = match[key]
                matches_list.append(match_item)
            entity_item['matches'] = matches_list
        result.append(entity_item)
    return result


def serialize_recognize_entities(recognize_entities):
    result = []
    for entity in recognize_entities:
        item = {}
        for key in ['category', 'confidence_score', 'length', 'offset', 'subcategory', 'text']:
            if key in entity:
                item[key] = entity[key]
        result.append(item)
    return result


@app.route('/ping')
def ping():
    return 'MS-ACS Service'


@app.route('/wiki_links', methods=['post'])
def wiki_links():
    response_body = {
        'code': 0,
        'content': None,
        'message': ""
    }
    data_body = request.get_json()
    global analysis_client
    if analysis_client is None:
        analysis_client = get_analysis_client()
    try:
        response = analysis_client.recognize_linked_entities(data_body)
        for doc in response:
            if not doc.is_error:
                result = serialize_linked_entities(doc.entities)
                response_body['code'] = 200
                response_body['content'] = result
            else:
                response_body['code'] = 500
                response_body['message'] = "doc is error"
        return response_body
    except Exception as e:
        response_body['code'] = 500
        response_body['message'] = repr(e)
        return response_body


@app.route('/entities', methods=['post'])
def entities():
    response_body = {
        'code': 0,
        'content': None,
        'message': ""
    }
    data_body = request.get_json()
    global analysis_client
    if analysis_client is None:
        analysis_client = get_analysis_client()
    try:
        response = analysis_client.recognize_entities(data_body)
        for doc in response:
            if not doc.is_error:
                result = serialize_recognize_entities(doc.entities)
                response_body['code'] = 200
                response_body['content'] = result
            else:
                response_body['code'] = 500
                response_body['message'] = "doc is error"
        return response_body
    except Exception as e:
        response_body['code'] = 500
        response_body['message'] = repr(e)
        return response_body


@app.route('/translation', methods=['post'])
def translation():
    response_body = {
        'code': 0,
        'content': None,
        'message': ""
    }
    data_body = request.get_json()
    text = data_body['text']
    to_language = data_body['to_language']
    try:
        result_json = get_translation(text, to_language)
        response_body['code'] = 200
        response_body['content'] = json.loads(result_json)
    except Exception as e:
        response_body['code'] = 500
        response_body['message'] = repr(e)
    return response_body


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5110)
