#!/usr/bin/env python

import argparse
import logging
import sys
from huecontroller import HueController
from phue import PhueRegistrationException

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-b', '--bridge', default=None)
    parser.add_argument('--verbose', action='store_true', default=False)

    subcmds = parser.add_subparsers(dest="command")
    listcmd = subcmds.add_parser('list')
    savecmd = subcmds.add_parser('save')
    savecmd.add_argument('name', default='default')
    loadcmd = subcmds.add_parser('load')
    loadcmd.add_argument('name', default='default')
    offcmd = subcmds.add_parser('off')
    oncmd = subcmds.add_parser('on')
    cntcmd = subcmds.add_parser('connect')
    cntcmd.add_argument('--bridge', required=True)

    args = parser.parse_args()

    if not args.verbose:
        logger = logging.getLogger('phue')
        logger.setLevel(logging.CRITICAL)

    try:
        ctl = HueController(args.bridge)
    except PhueRegistrationException as exp:
            print exp.message
    except Exception as exp:
        if args.bridge is None:
            sys.stderr.write('Could not connect to the bridge.\n'
                             'Did you register the app with:\n'
                             '\t\'huectl --bridge <hostname|IP> connect\'?\n')
        else:
            sys.stderr.write(exp.message)
        sys.exit(-1)

    if args.command == 'list':
        for cfg in ctl.configs:
            print(cfg)
    elif args.command == 'save':
        ctl.save_state(args.name)
    elif args.command == 'load':
        ctl.load_state(args.name)
    elif args.command == 'off':
        ctl.lights_off()
    elif args.command == 'on':
        ctl.lights_on()

