from flask import Flask, jsonify, render_template, request, send_file
import requests
import json
import os

HOST = "0.0.0.0"
IP = "192.168.1.32"

app = Flask(__name__)
up_folder="/FLASK/upload/"
@app.route('/', methods=['GET'])
def index():
    return render_template("racine.html")

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['File']
    filePath = os.path.join(up_folder, file.filename)
    newFilePath = os.path.splitext(filePath)[0]+'.ppm'
    try:
        file.save(filePath)
        os.system("convert "+filePath+" -resize 240x320! "+newFilePath)
        if(os.path.splitext(filePath)[1] != ".ppm"):
            os.remove(filePath)
    except:
        return jsonify({'ERROR': 'failed uploading '+file.filename}), 500
    return jsonify({'OK':file.filename+' uploaded'}), 200

@app.route('/list_display', methods=['GET'])
def listDisplay():
    str_out = ""
    all_files = json.loads(requests.get("http://"+IP+":5000/list").content)
    for f in all_files:
        nom_fichier=str(f)
        str_out+=nom_fichier+"&nbsp <a href=http://"+IP+":5000/display/"+nom_fichier+">"+"Afficher"+"</a>"+"&nbsp <a href=delete/"+nom_fichier+">"+"Supprimer"+"</a>"+"&nbsp <a href=http://"+IP+":5000/download/"+nom_fichier+">"+"Telecharger"+"</a>"+"<br>"
    return str_out

@app.route('/delete/<name>', methods=['GET'])
def DeleteFile(name):
    req = requests.delete("http://"+IP+":5000/delete/"+name)
    if(req.status_code == 500):
        return jsonify({'ERROR': 'failed deleting '+name}), 500
    return jsonify({'OK':name+' deleted'}), 200


if __name__ == "__main__":
    app.run(host=HOST, use_reloader=False, debug=True, port=800)
