#!/usr/bin/env python3
import argparse
import curses
from pathlib import Path
import subprocess
import sys
from time import sleep

indicator = "➤"

binding_up = [ord('k'), curses.KEY_UP]
binding_down = [ord('j'), curses.KEY_DOWN]
binding_accept = [ord('l'), ord(' '), ord('\n')]
binding_back = [ord('h'), ord('q'), curses.KEY_BACKSPACE]
binding_exit = [ord('Q')]

def show_pictures(path):
    files = sorted([str(f) for f in path.iterdir() if f.is_file() and f.suffix.lower() in ['.png', '.jpg', '.jpeg', '.gif']])
    files.insert(0, '/usr/bin/imvr')
    subprocess.call(files)
    return True

def show_select(win, path):
    if not path.is_dir():
        raise Exception("'" + str(path) + "' is not a directory!")
    dirs = sorted([d for d in path.iterdir() if d.is_dir()])
    if len(dirs) <= 0:
        return show_pictures(path)
    win.clear()
    sel = 0
    while True:
        for y, d in enumerate(dirs):
            win.addstr(y, 0, (indicator + " " if y == sel else "  ") + d.name + (" " * (curses.COLS - 2 - len(d.name))), curses.A_STANDOUT if y == sel else curses.A_NORMAL)
        c = win.getch()
        if c in binding_up:
            sel = max(0, sel - 1)
        elif c in binding_down:
            sel = min(len(dirs) - 1, sel + 1)
        elif c in binding_accept:
            if not show_select(win, dirs[sel]):
                return False
            win.clear()
        elif c in binding_back:
            return True
        elif c in binding_exit:
            return False

def select_ui(win, args):
    curses.curs_set(0)
    while show_select(win, args.dir) and args.kiosk:
        pass
    if args.kiosk:
        subprocess.call(['systemctl', 'poweroff'])
    return True # exited as expected

def retry(fun):
    last_return = False
    while not last_return:
        try:
            last_return = fun()
        except:
            pass # TODO save log file with error

def main():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--base-dir', type=Path, dest='dir', required=True)
    parser.add_argument('--kiosk', dest='kiosk', action='store_true')
    parser.add_argument('--build-desc-of', type=Path, dest='desc_path', default=None)
    args = parser.parse_args()
    if args.desc_path is not None:
        rel_path = args.desc_path.relative_to(args.dir)
        parts = list(rel_path.parts[:-1])
        parts.append(rel_path.stem)
        parts = [part.replace('_', ' ') for part in parts]
        print(str(' - '.join(parts)))
        return
    def run():
        curses.wrapper(select_ui, args)
    if args.kiosk:
        retry(run)
    else:
        run()

if __name__ == '__main__':
    main()
