import subprocess
from pathlib import Path

from flask import Flask, send_from_directory, request
from pynput.keyboard import Key, Controller
from pynput import keyboard

_static_dir = Path(__file__).parent / "mediaweb"

app = Flask(__name__, static_url_path="", static_folder=str(_static_dir))


@app.route("/execute", methods=['POST'])
def execute():
    action = request.values.get("id")
    entry = methods.get(action)
    if entry is None:
        return 'unknown action', 400
    m = entry[0]
    v = entry[1]
    m(v)
    return 'ok'


@app.route('/', methods=['GET'])
def upload_file():
    return send_from_directory(str(_static_dir), "index.html")


_keyboard_controller = Controller()


def media(k):
    _keyboard_controller.press(k)
    _keyboard_controller.release(k)


def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except AttributeError:
        k = key.name  # other keys
    if k in ['8']:  # keys of interest
        print('Key pressed: ' + k)
        slides(True)
    if k in ['9']:  # keys of interest
        print('Key pressed: ' + k)
        slides(False)


def slides(run):
    if run:
        subprocess.run("start c:\\views\\slider\\start.bat", shell=True)
    else:
        subprocess.run("start c:\\views\\slider\\stop.bat", shell=True)


methods = {"next": (media, Key.media_next),
           "prev": (media, Key.media_previous),
           "pause": (media, Key.media_play_pause),
           "runslides": (slides, True),
           "stopslides": (slides, False)
           }


def main():
    print('started app')
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    app.run(host="0.0.0.0")


if __name__ == '__main__':
    main()
