#!/usr/bin/env python
import sys
import termenu

def main():
    # Always connect stdin/stdout to the controlling terminal, even if redirected
    redirectedStdin = sys.stdin
    redirectedStdout = sys.stdout
    if not sys.stdin.isatty():
        sys.stdin = open("/dev/tty")
    if not sys.stdout.isatty():
        sys.stdout = open("/dev/tty", "w")

    from optparse import OptionParser, IndentedHelpFormatter
    class MyHelpFormatter(IndentedHelpFormatter):
        def format_description(self, description):
            return description

    description = """\
Shows an inline interactive menu. Menu items can be supplied as arguments,
via STDIN (if no arguments were given) or a file (using -f).
Menus can be vertical (multi-line) or one-line.

Examples:
    termenu.py Abort Retry Fail
    ls | termenu.py -
    termenu.py -f file_with_options.txt
"""
    parser = OptionParser(usage="Usage: %prog [items]", description=description, formatter=MyHelpFormatter(), add_help_option=False)
    parser.add_option("--help", dest="help", help="Show help message", action="store_true", default=False)
    parser.add_option("-f", "--file", dest="file", help="Take menu items from a file", metavar="FILE")
    parser.add_option("-v", "--vertical", dest="vertical", help="Display a vertical menu", action="store_true", default=True)
    parser.add_option("-h", "--horizontal", dest="vertical", help="Display a horizontal menu", action="store_false")
    parser.add_option("-t", "--title", dest="title", help="A title for the menu", default="")
    parser.add_option("-d", "--default", dest="default", help="Default item to select", metavar="OPTION")
    parser.add_option("-l", "--lines", dest="lines", type="int", help="Max lines for vertical menu", metavar="LINES", default=20)
    (options, args) = parser.parse_args()

    if options.help:
        parser.print_help()
        sys.exit(255)

    items = []

    try:
        if len(args) == 0:
            items = [l.strip() for l in redirectedStdin.readlines()]
        elif options.file:
            items = open(options.file).readlines()
        else:
            items = args
    except IOError, e:
        parser.error(str(e))

    if not items:
        parser.error("no menu items provided")

    if options.vertical:
        result = termenu.show_vertical_menu(options.title, items, default=options.default, height=options.lines)
    else:
        result = termenu.show_menu(options.title, items, default=options.default)

    if result:
        redirectedStdout.write(result + "\n")

if __name__ == "__main__":
    main()
