#!/usr/bin/env python
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Robotice CLI
"""


import os
import six
import sys

import argparse

from roboticeclient.client import Client as RoboticeClient

import logging

LOG = logging.getLogger(__name__)


class RoboticeShell(object):

    def _setup_logging(self, debug):
        log_lvl = logging.DEBUG if debug else logging.WARNING
        logging.basicConfig(
            format="%(levelname)s (%(module)s) %(message)s",
            level=log_lvl)
        logging.getLogger('iso8601').setLevel(logging.WARNING)
        logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)

    def _setup_verbose(self, verbose):
        if verbose:
            exc.verbose = 1

    def get_subcommand_parser(self, name):
        parser = self.get_base_parser()

        self.subcommands = {}
        subparsers = parser.add_subparsers(metavar='<subcommand>')
        submodule = import_named_module(name, 'shell')

        self._find_actions(subparsers, submodule)
        self._find_actions(subparsers, self)
        self._add_bash_completion_subparser(subparsers)

        return parser

    def get_base_parser(self):
        parser = argparse.ArgumentParser(
            prog='robotice',
            description="TODO",
            epilog=('See "%(arg)s" for help on a specific command.') % {
                'arg': 'robotice help COMMAND'
            },
            add_help=False,
            formatter_class=HelpFormatter,
        )

        # Global arguments

        parser.add_argument('-t', '--type',
                            default='robotice',
                            help=("type robotice or control"))

        parser.add_argument('--host',
                            default='127.0.0.1',
                            help=("host"))

        parser.add_argument('-p', '--port',
                            default=8004,
                            help=("port"))

        parser.add_argument('-a', '--action',
                            default="list",
                            help=("action"))

        parser.add_argument('-c', '--collection',
                            default="devices",
                            help=("collection"))

        parser.add_argument('-h', '--help',
                            action='store_true',
                            help=argparse.SUPPRESS)

        parser.add_argument('--version',
                            action='version',
                            version="0.0.1",
                            help=("Shows the Robotice version."))

        parser.add_argument('-d', '--debug',
                            default=True,
                            action='store_true',
                            help=('Defaults to %(value)s.') % {
                                'value': 'env[ROBOTICE_DEBUG]'
                            })

        parser.add_argument('-v', '--verbose',
                            default=False, action="store_true",
                            help=("Print more verbose output."))

        return parser

    def main(self, argv):
        # Parse args once to find role
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self._setup_logging(options.debug)
        self._setup_verbose(options.verbose)

        client = RoboticeClient(type=options.type, host=options.host, port=options.port)

        mgr = getattr(client, options.collection, None)
        action = getattr(mgr, options.action, None)
        print action()



class HelpFormatter(argparse.RawDescriptionHelpFormatter):

    def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(HelpFormatter, self).start_section(heading)


def main(args=None):
    try:
        if args is None:
            args = sys.argv[1:]

        RoboticeShell().main(args)
    except KeyboardInterrupt:
        print "... bye"
        sys.exit(130)
    except Exception as e:
        if '--debug' in args or '-d' in args:
            raise e
        # ugly hack
        RoboticeShell().get_base_parser().print_help()
        
        sys.exit(1)

if __name__ == "__main__":
    main()
