from flask import Flask, jsonify, render_template, request, send_file
import os
import json
import signal
import shutil
import random
from subprocess import check_output
# The interface to bind to (0.0.0.0 means all interfaces)
HOST = "0.0.0.0"
up_folder="/FLASK/upload/"
def get_pid(name):
    return int(check_output(["pidof","-s",name]))
app = Flask(__name__)
pid=get_pid("display")


@app.route('/download/<file>', methods=['GET'])
def download(file):
    try:
        return send_file(up_folder+file)
    except:
        return jsonify({'ERROR': 'No file to download '}), 500

@app.route('/delete/<file>', methods=['DELETE'])
def delete(file):
    file_path = os.path.join(up_folder, file)
    try:
        os.remove(file_path)
    except:
        return jsonify({'ERROR': 'failed deleting '+file}), 500
    return jsonify({'OK':file+' deleted'}), 200

@app.route('/hello/<name>', methods=['GET'])
def hello(name):
    return jsonify({'OK':'Hello '+name}), 200

@app.route('/list', methods=['GET'])
def list():
    files=[]
    for f in os.listdir(up_folder):
        if os.path.isfile(os.path.join(up_folder,f)):
            files.append(f)
    #return jsonify(onlyfiles)
    return json.dumps(files)

@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"):#si le fichier de base etait deja un ppm
            os.remove(filePath)
    except:
        return jsonify({'ERROR': 'failed uploading '+file.filename}), 500
    return jsonify({'OK':file.filename+' uploaded'}), 200
@app.route('/display/<image>', methods=['GET'])
def display(image):
    #if not os.path.exists("FLASK/to_display/img_to_disp.ppm"):
    try:
        os.open("/FLASK/to_display/img_to_disp.ppm", os.O_CREAT | os.O_EXCL)#on regarde si on a deja une immage a afficher
        shutil.copyfile(up_folder+image, "/FLASK/to_display/"+image)
        os.rename("/FLASK/to_display/"+image,"/FLASK/to_display/img_to_disp.ppm")
        os.kill(pid, signal.SIGUSR1)
    except Exception as e:
        #os.remove(".tmp/"+name)
        return jsonify({'ERROR': 'Cant show image'}), 500
    return jsonify({'OK':'Image displayed'}), 200

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