#!/usr/bin/env python3

from enum import Enum, auto
from fcntl import ioctl
from json import loads
from os import read
from select import select
from struct import unpack
from subprocess import run as run_process
from sys import argv, stderr, stdin, stdout
from termios import TCSADRAIN, TIOCGWINSZ, tcgetattr, tcsetattr
from tty import setraw


class Key(Enum):
    LEFT = auto()
    UP = auto()
    RIGHT = auto()
    DOWN = auto()
    ENTER = auto()
    ESCAPE = auto()


class MenuAction(Enum):
    QUIT_ENTIRELY = auto()
    LEAVE_SUBMENU = auto()


def cursor_visible(state):
    if state:
        stdout.write("\033[?25h")
    else:
        stdout.write("\033[?25l")


def secondary_screen(state):
    if state:
        stdout.write("\033[?1049h")
    else:
        stdout.write("\033[?1049l")


def execute(cmd):
    terminal_release()

    run_process([cmd])
    input("Hit ENTER to return to menu")

    terminal_grab()


def getkey():
    fd = stdin.fileno()
    old_settings = tcgetattr(fd)
    try:
        setraw(stdin.fileno())

        buf = b""
        timeout = 60
        while True:
            r, w, x = select([stdin.fileno()], [], [], timeout)
            if r:
                timeout = 0.01
                ch = read(stdin.fileno(), 1)
                buf += ch
                if ch != b"\033" and ch != b"[":
                    break
            elif timeout < 60:
                # No known sequence, but might be a single Escape. This
                # assumes that the terminal provides the entire sequence
                # within our reduced 'timeout'.
                break
    finally:
        tcsetattr(fd, TCSADRAIN, old_settings)

    if buf == b"\033[D":
        return Key.LEFT
    if buf == b"\033[A":
        return Key.UP
    if buf == b"\033[C":
        return Key.RIGHT
    if buf == b"\033[B":
        return Key.DOWN
    if buf == b"\033":
        return Key.ESCAPE
    if buf == b"\r":
        return Key.ENTER

    return buf.decode("UTF-8")


def termsize():
    fd = stdout.fileno()
    h, w, _, _ = unpack("hhhh", ioctl(fd, TIOCGWINSZ, b" " * 8))
    return h, w


def status(depth, width):
    sz_corner = 2

    if depth > 0:
        msg_left = " " + "../ " * depth
    else:
        msg_left = ""

    msg_right = f" q: Quit "

    len_fill = width - 2 * sz_corner - len(msg_left) - len(msg_right)

    msg = msg_left + "═" * len_fill + msg_right
    msg = msg[: width - 2 * sz_corner]

    stdout.write("╚═")
    stdout.write(msg)
    stdout.write("═╝")


def title(t, width):
    stdout.write("╔")
    front = (width - 1 - 1 - len(t)) // 2
    #                |   |
    #                |   \- Space before title.
    #                |
    #                \- Left corner.
    stdout.write("═" * front)
    stdout.write(" ")
    stdout.write("\033[1m")
    stdout.write(t)
    stdout.write("\033[0m")
    stdout.write(" ")
    back = width - 1 - front - 1 - len(t) - 1 - 1
    #              |           |            |   |
    #              |           |            |   \- Right corner.
    #              |           |            |
    #              |           |            \- Space after title.
    #              |           |
    #              |           \- Space before title.
    #              |
    #              \- Left corner.
    stdout.write("═" * back)
    stdout.write("╗")


def terminal_grab():
    secondary_screen(True)
    cursor_visible(False)
    stdout.flush()


def terminal_release():
    cursor_visible(True)
    secondary_screen(False)
    stdout.flush()


def run(menu, depth):
    margin = 4

    offset = 0
    sel = 0
    while True:
        height, width = termsize()

        stdout.write("\033[H")

        # Overwrite top margin.
        stdout.write(" " * width * (margin // 2))

        stdout.write(" " * margin)
        title(menu["title"], width - 2 * margin)
        stdout.write(" " * margin)

        space_for_items = height - 1 - 1 - margin

        i = offset
        shown = 0
        while i < len(menu["items"]) and shown < space_for_items:
            itemtext = menu["items"][i].get("title", "")
            if "items" in menu["items"][i]:
                itemtext = "→ " + itemtext
            elif "separator" not in menu["items"][i]:
                itemtext = "  " + itemtext

            # 4 = border left + border right + space before and after title
            fill = width - 2 * margin - 4 - len(itemtext)

            stdout.write(" " * margin)
            stdout.write("║ ")

            if i == sel:
                stdout.write("\033[7m")
            else:
                stdout.write("\033[32m")
            if "separator" in menu["items"][i]:
                stdout.write("─" * fill)
            else:
                stdout.write(itemtext)
                stdout.write(" " * fill)
            stdout.write("\033[0m")
            stdout.write(" ║")
            stdout.write(" " * margin)

            i += 1
            shown += 1

        while shown + 1 + margin // 2 < height - margin // 2 - 1:
            #             |   \_________/            \_________/   |
            #             |        |                      |        \- Status line.
            #             |        |                      |
            #             |        |                      \- The other half below.
            #             |        |
            #             |        \- Half of the margin goes above the menu.
            #             |
            #             \- Titel line.

            stdout.write(" " * margin)
            stdout.write("║ ")
            stdout.write(" " * (width - 2 * margin - 4))
            stdout.write(" ║")
            stdout.write(" " * margin)
            shown += 1

        stdout.write(" " * margin)
        status(depth, width - 2 * margin)
        stdout.write(" " * margin)

        # Overwrite bottom margin.
        stdout.write(" " * width * (margin // 2))

        stdout.flush()

        response = getkey()
        if response in (Key.LEFT, Key.ESCAPE, "h"):
            return MenuAction.LEAVE_SUBMENU
        elif response in (Key.DOWN, "j"):
            sel += 1
            while sel < len(menu["items"]) and "separator" in menu["items"][sel]:
                sel += 1
        elif response in (Key.UP, "k"):
            sel -= 1
            while sel > 0 and "separator" in menu["items"][sel]:
                sel -= 1
        elif response in (Key.RIGHT, Key.ENTER, "l"):
            if "command" in menu["items"][sel]:
                execute(menu["items"][sel]["command"])
            elif "items" in menu["items"][sel]:
                if run(menu["items"][sel], depth + 1) == MenuAction.QUIT_ENTIRELY:
                    return MenuAction.QUIT_ENTIRELY
        elif response == "q":
            return MenuAction.QUIT_ENTIRELY

        sel = max(0, sel)
        sel = min(sel, len(menu["items"]) - 1)

        if sel >= offset + space_for_items:
            offset += 1
        elif sel < offset:
            offset -= 1


if __name__ == "__main__":
    if len(argv) < 2:
        try:
            with open("mymenu.json") as fp:
                menu = loads(fp.read())
        except FileNotFoundError:
            print(f"Usage: {argv[0]} [mymenu.json]", file=stderr)
            exit(1)
    else:
        with open(argv[1]) as fp:
            menu = loads(fp.read())

    try:
        terminal_grab()
        run(menu, 0)
    finally:
        terminal_release()
