#!/usr/bin/python

# Copyright C 2002-2003 by Isilon Systems, Inc. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
# 
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
# 
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems. 
#  
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.
#
# $Id: isi_lcd_ctl 60606 2006-12-12 01:54:52Z jroberson $
"""
LCD Control

Commands:

 prompt (question, option1, option2, ...)
 progress (label, percent)
 
Options:
 -s sid      # Screen ID
 -t timeout  # Timeout
 -p priority # Priority

"""

import sys
import getopt
import os.path
import isi.ui.lcd.library as lib
import isi.ui.lcd.library as lcd
import isi.ui.lcd.screens as scr

# Setup logging
import logging
log = logging.getLogger('isi_lcd_ctl')

# Methods

def _common_options(opts, screen):
    for o, a in opts:
        if o == '-p':
            screen._priority = int(a)
        if o == '-t':
            screen._timeout = int(a)

def lcd_display(action, argv):
    """
    Display a static screen on the LCD, with no way to exit (except timeout).
    """

    opts, argv = getopt.getopt(argv, 'p:t:')

    screen = scr.StaticScreen(argv[0])
    screen._can_exit = False
    _common_options(opts, screen)

    result = lcd.show(screen)

def lcd_prompt(action, argv):
    """
    Create a simple StringInputScreen with the given label.

    After the LCD screen has completed, the contents of the input will be
    printed to stdout.
    """

    opts, argv = getopt.getopt(argv, 'p:t:')

    screen = scr.StringInputScreen(argv[0])
    _common_options(opts, screen)

    result = lcd.show(screen)

    print result
    sys.exit(0)

def lcd_choose(action, argv):
    opts, argv = getopt.getopt(argv, 'p:t:')

    screen = scr.ListInputScreen(argv[0], argv[1:])
    _common_options(opts, screen)

    result = lcd.show(screen)

    try:
        sys.exit(argv[1:].index(result))
    except SystemExit:
        raise
    except:
        sys.exit(255)

def lcd_progress(action, argv):
    opts, argv = getopt.getopt(argv, 'p:t:s:m:')

    sid = None
    meter = 0

    for o, a in opts:
        if o == '-s':
            sid = int(a)
        if o == '-m':
            meter = int(a)

    screen = scr.ProgressMeterScreen(argv[0], meter)
    _common_options(opts, screen)

    lcd = lib.LCDClient(screen)

    lcd.start(sid)

    print lcd._sid

def lcd_cancel(action, argv):
    opts, argv = getopt.getopt(argv, 's:')

    sid = None

    lcd = lib.LCDClient()

    for o, a in opts:
        if o == '-s':
            sid = int(a)

    if (sid):
        print 'Cancelling sid:', sid
        lcd.cancel(sid)

class Action:
    def __init__(self, name, chars, f, args):
        self.name = name
        self.chars = chars
        self.func = f
        self.args = args

def warnx(s):
    print >> sys.stderr, "%s: %s" % (prog, s)

def usage(a, s = None):
    if s: warnx(s)
    if a:
        print >> sys.stderr, "usage: isi_lcd_ctl %s %s" % (a.name, a.args)
        sys.exit(s and 1 or 0)
    print >> sys.stderr, "Usage: isi_lcd_ctl [-h]"
    for a in actions:
        print >> sys.stderr, "       isi_lcd_ctl %s %s" % (a.name, a.args)
    sys.exit(s and 1 or 0)

actions = [
    Action("prompt", 3, lcd_prompt, "[-p pri] [-t timeout] label"),
    Action("choose", 3, lcd_choose, "[-p pri] [-t timeout] label option(s)..."),
    Action("progress", 3, lcd_progress, "[-p pri] [-t timeout] label"),
    Action("display", 3, lcd_display, "[-p pri] [-t timeout] label"),
    Action("cancel", 2, lcd_cancel, "[-s sid]"),
]

def main():
    if len(sys.argv) == 1:
        usage(None, "Too few arguments.")
    for action in actions:
        if not action.chars <= len(sys.argv[1]) <= len(action.name):
            continue
        if sys.argv[1] == action.name[:len(sys.argv[1])]:
            if len(sys.argv) == 3 and sys.argv[2] == '-h':
                usage(action)
                return 0
            try:
                action.func(action, sys.argv[2:])
            except getopt.GetoptError:
                return usage(action, "Invalid arguments to isi_lcd_ctl %s." %
                    action.name)
            return 0
    if sys.argv[1] == "-h":
        usage(None)
    if sys.argv[1] == "-l":
        for action in actions:
            print action.name, 'a'
    else:
        usage(None, "Unknown command '%s'." % sys.argv[1])

if __name__ == "__main__":
    prog = os.path.basename(sys.argv[0])
    logging.basicConfig()
    logging.getLogger('').setLevel(logging.ERROR)
    #logging.getLogger('lcd').setLevel(logging.DEBUG)
    #logging.getLogger('isi_lcd_ctl').setLevel(logging.DEBUG)
    main()

# vim:set filetype=python:
