#!/usr/bin/env python3
#
# Copyright (C) 2022 Leandro Lisboa Penz <lpenz@lpenz.org>
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
"""
Choose a man page to read interactively from a menu with fuzzy search
"""

import os
import re
import argparse
import subprocess

import tuzue

PATH = "/usr/share/man"


def generator(mandict):
    yield "quit"
    labelre = re.compile(re.escape(PATH) + r"/(man[0-9]/.*)\.[0-9]\S*\.gz")
    for root, _, files in os.walk(PATH):
        for filename in files:
            path = os.path.join(root, filename)
            labelmatch = labelre.match(path)
            if labelmatch:
                label = labelmatch.group(1)
            else:
                continue
            mandict[label] = path
            yield label


def manmenu():
    mandict = {}
    view = tuzue.view.View(title="Man page menu", generator=generator(mandict))
    while True:
        with tuzue.ui.curses.context() as ui:
            done = False
            while not done:
                ui.show(view)
                done = ui.interact(view)
        item = view.selected_item()
        if item == "quit":
            return
        subprocess.run(["man", "-P/usr/bin/less", mandict[item]], check=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--version", "-V", action="version", version="%(prog)s " + tuzue.__version__
    )
    parser.parse_args()
    manmenu()


if __name__ == "__main__":
    main()
