from flask import Flask, Response, jsonify, request
from flask_cors import CORS

import config
from wiktextract_wrapper import Wiktextract

app = Flask(__name__)
CORS(app)


@app.route("/", methods=["GET"])
def index():
    c = request.remote_addr
    response = f"<p>Server is running, your ip is {c}</p>"
    return Response(response, 200)


@app.route("/search/<wiktlang>/<wordlang>/<word>", methods=["GET"])
def search(wiktlang, wordlang, word):
    if wiktlang not in config.supported_wiktlangs:
        return jsonify({"error": f"Language {wiktlang} not supported"}), 400

    wiktextractor = Wiktextract(wiktlang, wordlang)
    try:
        resp = wiktextractor.parse_page(word)
        if resp:
            return jsonify(resp)
        else:
            return (
                jsonify(
                    {
                        "error": f"{word} is unknown in “{wordlang}” in {wiktlang}.wiktionary.org."
                    }
                ),
                404,
            )

    except Exception as e:
        print(e)

        return jsonify({"error": "Parsing page resulted in error: " + str(e)}), 500
    finally:
        wiktextractor.wxr.wtp.db_conn.close()
        if wiktextractor.wxr.thesaurus_db_conn:
            wiktextractor.wxr.thesaurus_db_conn.close()


if __name__ == "__main__":
    app.run(host=config.host, port=config.port, debug=config.debugging)