#!/usr/bin/env python

"""Usage example of Python module for NooLite USB stick.

You can use this example like a console control.
Just copy it to PATH directory:
    sudo cp example.py /usr/local/bin/noolite
Or if only for your user:
    mkdir -p ~/bin && cp example.py ~/bin/noolite

Do not forget set the execute bit via chmod.

Latest version at: https://github.com/Sicness/pyNooLite
"""

import sys

try:
    import noolite
except ImportError:
    sys.stderr.write("Please, install last pyusb\n")
    sys.exit(-1)

__author__ = "Anton Balashov"
__license__ = "GPL v3"
__maintainer__ = "Anton Balashov"
__email__ = "Sicness@darklogic.ru"


def help():
    print("""
    USAGE:
    on <ch>         Turn power ON for specified channel
    off <ch>        Turn power OFF for specified channel
    switch <ch>     Switch between ON and OFF for specified channel
    set <ch> <lvl>  Set power level for specified channel
    save <ch>       Save state  for specified channel as a scenario
    load <ch>       Call saved scenario for specified channel
    bind <ch>       Send binding signal for specified channel
    unbind <ch>     Send unbinding signal for specified channel

    Channels should be between 0 and 7.
    Level should be between 0 and 120.

    Examples:
        $ ./noolite on 1
        $ ./noolite set 0 115
    """)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        help()
        sys.exit(0)

    cmd = sys.argv[1]
    ch = sys.argv[2]
    if cmd == 'set':
        if len(sys.argv) == 4:
            lvl = int(sys.argv[3])
        else:
            sys.stderr.write(
                "'set' command must have additional 'lvl' argument.\n")
            help()
            sys.exit(1)

    n = noolite.NooLite()
    cmds = {
        'on': n.on,
        'off': n.off,
        'switch': n.switch,
        'set': n.set,
        'save': n.save,
        'load': n.load,
        'bind': n.bind,
        'unbind': n.unbind
    }

    if cmd not in cmds:
        sys.stderr.write("Unknown command: %s.\n" % (cmd))
        help()
        sys.exit(4)

    try:
        if sys.argv[1] == 'set':
            cmds[cmd](ch, lvl)
        else:
            cmds[cmd](ch)
    except (TypeError, ValueError, noolite.NooLiteErr) as err:
        sys.stderr.write(str(err) + ".\n")
        sys.exit(3)
