#!/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.
"""
Simple interactive directory navigation using tuzue, for testing purposes

After a path is selected via the "." entry, it's printed to stderr and the program
exists with 0.
"""

import sys
import os
import argparse
import time

import tuzue


def splitpath(path):
    pathlist = []
    while path != "/":
        (path, tail) = os.path.split(path)
        pathlist.append(tail)
    pathlist.reverse()
    return pathlist


def generator(delay=None):
    # We use a generator just to show the capabilities:
    delay = delay or 0.01
    time.sleep(delay)
    yield "."
    time.sleep(delay)
    yield ".."
    for entity in os.listdir("."):
        time.sleep(delay)
        yield entity


def navdir(path, delay):
    title = "/" + "/".join(path)
    view = tuzue.view.View(title=title, generator=generator(delay))
    with tuzue.ui.curses.context() as ui:
        while True:
            done = False
            while not done:
                ui.show(view)
                done = ui.interact(view)
            item = view.selected_item()
            if item == ".":
                return (True, path)
            elif item == "..":
                if path:
                    os.chdir("..")
                    path.pop()
                return (False, path)
            elif os.path.isdir(item):
                os.chdir(item)
                path.append(item)
                return (False, path)
            # Otherwise we just ignore the selection.


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--version", "-V", action="version", version="%(prog)s " + tuzue.__version__
    )
    parser.add_argument(
        "--delay",
        "-d",
        dest="delay",
        action="store",
        type=float,
        default=0.01,
    )
    args = parser.parse_args()
    cwd = os.getcwd()
    path = splitpath(cwd)
    done = False
    while not done:
        (done, path) = navdir(path, delay=args.delay)
    sys.stderr.write("/{}\n".format("/".join(path)))


if __name__ == "__main__":
    main()
