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

import config
from get_wikicode import get_wikicode
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):
    wikicode = get_wikicode(word, wiktlang)
    if wikicode:
        en_wiktextract = Wiktextract("en", wordlang)
        try:
            resp = en_wiktextract.parse_page(word, wikicode)
            return jsonify(resp)

        except Exception as e:
            print(e)
            resp = f"""<!doctype html>
                    <html>
                    <head>
                        <title>Error</title>
                    </head> 
                    <body>
                        <h1>{word}</h1>
                        <p>{e}</p>  
                    </body>
                    </html>"""
            status = 404
            mimetype = "text/html"
        finally:
            en_wiktextract.page_handler.wxr.wtp.db_conn.close()

    else:
        resp = f"""<!doctype html>
                  <html>
                  <head>
                      <title>Error</title>
                  </head>
                  <body>
                      <h1>{word}</h1>
                      <p>{word} is unknown in “{wordlang}” in {wiktlang}.wiktionary.org.</p>
                  </body>
                  </html>"""
        status = 404
        mimetype = "text/html"
    return Response(resp, status=status, mimetype=mimetype)


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