#!/usr/bin/env python
""" furtive command line tool """


import os
import sys
import logging
import argparse

import yaml

from furtive import Furtive


def parse_args(args):
    """ Method to parse command line arguments.

        :param args: command line arguments as typed on the commadn line
        :type args: str

        :return: parsed arguments from argparse()
        :rtype: argparse.Namespace()
    """

    action_help = ''' Which action to perform:
      check - check the integrity of files listed in the manifest.
      create - create a new manifest from the files inthe directory
               specified by the --basedir argument.
    '''

    parser = argparse.ArgumentParser(description='Hash files within a directory.')
    parser.add_argument('--basedir', action='store', default='.',
                        help='''Directory containing files that will be
                             checked. Default: .''')
    parser.add_argument('--manifest', action='store', dest='manifest_path',
                        default=None,
                        help='''Location of the manifest file. Manifests may
                                be located outside the directory indicated by
                                --basedir. Must provide path and filename of
                                the manifest file.
                                Default: <basedir>/.manifest.yaml''')
    parser.add_argument('--log-level', action='store', dest='log_level',
                        choices=('debug', 'info', 'warn', 'error', 'critical'),
                        default='info')
    parser.add_argument('action', choices=('create', 'compare'),
                        help=action_help,
                        nargs=1)
    parsed_args = parser.parse_args(args)
    parsed_args.action = parsed_args.action.pop()

    if parsed_args.manifest_path is None:
        parsed_args.manifest_path = os.path.join(parsed_args.basedir,
                                                 '.manifest.yaml')

    return parsed_args

def main():
    """ Starting point of the furtive command line tool """

    args = parse_args(sys.argv[1:])

    log_format = '%(asctime)s [%(levelname)s]: %(message)s'
    date_format = '%c %Z'
    numeric_level = getattr(logging, args.log_level.upper(), None)
    logging.basicConfig(level=numeric_level,
                        format=log_format,
                        datefmt=date_format)

    furtive = Furtive(args.basedir, args.manifest_path)

    if args.action == 'create':
        furtive.create()
    elif args.action == 'compare':
        changes = furtive.compare()
        sys.stdout.write(yaml.safe_dump(changes, default_flow_style=False))

if __name__ == '__main__':
    main()
