#!venv/bin/python

from flask import Flask, request, render_template
from api import API
from voice_recognition import Voice
import sys
import threading
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import *


APP = Flask(__name__)
api = API()
voice = Voice()

messages = []


# The following method shows the user the GUI and does the backend connections to the API.
@APP.route('/', methods=['GET', 'POST'])
def index():
    global messages
    system_prompt = 'You are a helpful assistant.'
    system = 'Your system prompt is: \"'+system_prompt+'\" The following is your chat log so far: \n'

    if request.method == 'POST':
        option = request.form['option']

        user_message = request.form['user_message']

        if option == "voice":
            user_message = voice.listen()
            messages.append(f"User: {user_message}")
        elif option == "chat":
            messages.append(f"User: {user_message}")

        for line in messages:
            system += line + '\n'

        system += "The chat log is now finished."

        ai_response = "AI: " + api.send_message(user_message, 5, system)
        messages.append(ai_response)

    return render_template('index.html', messages=messages)


@APP.route('/faq')
def faq():
    return render_template('faq.html')


@APP.route('/documentation')
def contact():
    return render_template('documentation.html')


if __name__ == '__main__':
    qapp = QApplication(sys.argv)

    view = QWebEngineView()

    view.setGeometry(100, 100, 1280, 720)
    view.setWindowTitle("InterstellarAI")

    view.setUrl(QUrl("http://localhost:5000"))

    view.show()

    def run_flask():
        APP.run()

    def stop_flask():
        thread.join()
        qapp.quit()

    thread = threading.Thread(target=run_flask)
    thread.daemon = True
    thread.start()

    qapp.aboutToQuit.connect(stop_flask)

    sys.exit(qapp.exec_())
