#!python

# The basic imports:
from hexes import (
    Application,
    Box,
    Style,
)
from hexes.behaviors import quit

# We're going to use this in the logic below; not part of Hexes.
import subprocess


# Layout
#
# You can nest boxes indefinitely, though some layouts may fail on some screen
# sizes. You can specify text for boxes, whether that text should be flowed or
# treated as fixed, whether child boxes should be laid out horizontally or
# vertically, height and width for boxes, etc.
root = Box(
    style=Style(
        layout=Style.Layout.Horizontal,
    ),
    children=(
        Box(
            children=(
                Box(),
                Box(
                    style=Style(
                        height=3,
                    ),
                ),
            ),
        ),
        Box(
            style=Style(
                width=20,
            ),
        ),
    ),
)

# Logic
#
# Instantiate the application with the layout attached.
# Register any pre-defined behaviors you want (right now, that's only `quit`)
app = Application(root=root)
app.register('q', quit)


# Define custom behavior with the `@app.on` decorator. This decorator
# requires an event identifier, which is either 'ready' or a key identifier
# as returned by `curses.window.getkey`
@app.on('ready')
def show_files(app):
    # For this example, we're just gonna output an `ls` of the local directory.
    ls = str(subprocess.check_output('ls'), 'utf-8')
    # Obviously, how you identify and access boxes in a layout needs to be
    # improved; this is horrible:
    if app.root.children[0].children[0].text != ls:
        app.root.children[0].children[0].text = ls
    # To run a task forever, you have to tell it to schedule itself again:
    app.loop.create_task(show_files(app))


# Run
#
# The context manager helps us clean up no matter what exceptional exit
# conditions we have.
with app:
    app.run()
