#!/usr/bin/env python

import pycommand
import sys


class BasicExampleCommand(pycommand.CommandBase):
    '''An example of a basic CLI program

    This is an example that demonstrates the handling of all possible
    settings for the optional arguments, managed via the `optionList`.
    This example does not handle positional arguments.

    '''
    usagestr = 'usage: basic-example [options]'
    description = __doc__.split('\n')[0]

    # optionList is a tuple of 2-tuples, in format:
    # (long-option, (short-option, argument, help-information))
    #
    # The order in which you define the options will be the order
    # in which they will appear in the usage message
    optionList = (
        ('help', ('h', False, 'show this help information')),

        # To specify that an option requires an argument just add a
        # string that describes it
        ('file', ('f', '<filename>', 'use specified file')),

        # Use an empty string to ommit short option. Long option names
        # cannot be ommitted, since they are used as dictionary keys in
        # `self.flags` which holds the validated input
        ('version', ('', False, 'show version information')),
    )

    def run(self):
        '''The `run` method of the main command

        You need to define a method in your class that actually deals
        with any options that the user of your program has set. We call
        it `run` here, but you can name it whatever you want.

        After the object has been created, there are 4 instance
        variables ready for you to use to write the flow of the program.
        In this example we only use the following three::

            error -- Thrown by GetoptError when parsing illegal
                     arguments

            flags -- Object/dict of parsed options and corresponding
                     arguments, if any.

            usage -- String with usage information. The string
                     is compiled using the values found for `usagestr`,
                     `description`, `optionList` and `usageTextExtra`.

        '''
        if self.flags.help:
            print(self.usage)
            return 0
        elif self.flags.version:
            print('Python version ' + sys.version.split()[0])
            return 0
        elif self.flags.file:
            print('filename = ' + self.flags['file'])
            return 0

        print('Program completed. Try adding "--help"')

if __name__ == '__main__':
    # Shortcut for reading from sys.argv[1:] and sys.exit(status)
    pycommand.run_and_exit(BasicExampleCommand)

    # The shortcut is equivalent to the following:

    # cmd = $classname(sys.argv[1:])
    # if cmd.error:
    #     print('error: {0}'.format(cmd.error))
    #     sys.exit(1)
    # else:
    #     sys.exit(cmd.run())
