
import json
import copy
import requests
from werkzeug.utils import secure_filename
import time
import os

from flask import Flask, request, jsonify, redirect, url_for, flash, render_template
from flask_cors import CORS

import KCALLMUtilities
import KCALLMConst
import KCALLMMain


# Run app
app = Flask(__name__)
CORS(app)

# Ensure there's a folder to save the uploaded files
UPLOAD_FOLDER = os.path.join(os.getcwd(), "tmp", "uploads")
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
    
#
#  ex: http://127.0.0.1:5000/chat/?prompt=un%20moteur%20de%20100W
#
#------------------------------------
# Route for ping
#  ex: http://127.0.0.1:2525/ping
#------------------------------------
@app.route('/ping/')
def ping():
    html = "<!DOCTYPE html> \
        <html> \
        <head><title>Hello Image recognition</title></head> \
        <body><h1>Hello World!</h1></body> \
        </html>"
    return html


#-------------------------------------
# Route for searching by prompt
#  ex: http://127.0.0.1:2525/searchByPrompt?speech=une banane
#-------------------------------------
"""
@app.route('/searchByPrompt/', methods=["GET"])
def searchByPrompt():

    # Build event
    mess = request.args.get('speech', default=None, type=str)
    ctx = KCALLMConst.INTENT_TEXT_FOOD_AND_ACTIVITY
    comment = "Search by prompt"
    imagePath = ""
    image64 = ""
    test = 1
    llmid = ""
    origin = "DS"
    event = KCALLMUtilities.buildEvent(mess, imagePath, image64, ctx, comment, test, llmid, origin)

    # Execute
    result = KCALLMMain.runEvent(event)

    return result
"""

#-------------------------------------
# Route for searching by image
#  ex: http://127.0.0.1:2525/searchByImage
#-------------------------------------
@app.route('/searchByImage/', methods=["POST"])
def searchByImage():

    # Read file
    print(request.files)
    if 'uploaded_file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['uploaded_file']
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)

    # Read
    filePath = ''
    if file:
        filename = secure_filename(file.filename)
        filePath = os.path.join(UPLOAD_FOLDER, filename)
        file.save(filePath)

    # Build event
    mess = ""
    print("Encoded image: " + filePath)
    ctx = KCALLMConst.INTENT_IMAGE_ACTIVITY
    comment = "Search by upload"
    image64 = KCALLMUtilities.encodeImage(filePath)
    test = 1
    llmid = ""
    origin = "DS"
    event = KCALLMUtilities.buildEvent(mess, filePath, image64, ctx, comment, test, llmid, origin)

    # Execute
    result = KCALLMMain.runEvent(event)

    return result


if __name__ == '__main__':
    app.run(debug=True, port=2525)
