#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Usage:
    gitberg config
    gitberg library [status]
    gitberg clone <book_repo_name>
    gitberg (fetch | make | push | upload | metadata) <book_id> [options]
    gitberg get <book_id> [options]
    gitberg update [options]
    gitberg report <book_identity>
    gitberg all BOOKID BOOKIDEND [options]
    gitberg list <book_id_list> [options]
    gitberg apply <action> <book_repo_name>

Arguments:
    <book_repo_name> -- The name of a repo in Gitenberg, `Frankenstein_84`
    <target> -- a file path, example, where to clone a book
    <action> -- action to apply to repo

Options:
    -v --logging (debug | info | error)
    --rdf_library <rdf_library>         where are you storing rdf files
"""
# TODO  use `--` to separate arguments and files
#       ex: `git checkout -b foo -- file file1 file2
import logging
import sys

from docopt import docopt

from gitenberg import __version__
from gitenberg import Book
from gitenberg import clone
from gitenberg import config
from gitenberg import upload_all_books, upload_list
from gitenberg import library
from gitenberg import actions



def setup_logging(arguments):
    """ creates a logger with our hard-coded configuration
    takes: a docopt arguments object instance
    """
    logger = logging.getLogger('')
    logging.basicConfig(filename='./gitburg.log', level=logging.DEBUG)
    #stdout_handler = logging.StreamHandler(sys.stdout)
    #logger.addHandler(stdout_handler)


    if ('--logging' or '-v') in arguments:
        # if
        log_level = arguments['--logging']
        if log_level == 'debug':
            logger.setLevel(logging.DEBUG)
        elif log_level == 'info':
            logger.setLevel(logging.INFO)
        elif log_level == 'error':
            logger.setLevel(logging.ERROR)

    return logger


if __name__ == '__main__':
    arguments = docopt(__doc__, version=__version__)

    logger = setup_logging(arguments)
    try:
        if '--rdf_library' in arguments:
            rdf_library = arguments['--rdf_library']
        else:
            rdf_library = config.data.get('rdf_library', None)

        if arguments['<book_id>'] is not None:
            book = Book(arguments['<book_id>'])
            book.parse_book_metadata(rdf_library)

        if arguments['fetch']:
            logging.info("fetching a PG book: {0}".format(arguments['<book_id>']))
            book.fetch()

        elif arguments['make']:
            logging.info("making a local git repo for: {0}".format(arguments['<book_id>']))
            book.make()

        elif arguments['push']:
            logging.info("making a local git repo for: {0}".format(arguments['<book_id>']))
            book.push()

        elif arguments['upload']:
            logging.info("making a local git repo for: {0}".format(arguments['<book_id>']))
            book.push()

        elif arguments['metadata']:
            print book.meta.__unicode__()

        elif arguments['all']:
            upload_all_books(arguments['BOOKID'], arguments['BOOKIDEND'], rdf_library=rdf_library)

        elif arguments['list']:
            upload_list(arguments['<book_id_list>'], rdf_library=rdf_library)

        elif arguments['config']:
            config.check_config()

        elif arguments['library']:
            library()

        elif arguments['update']:
            raise NotImplementedError

        elif arguments['report']:
            raise NotImplementedError

        elif arguments['clone']:
            # TODO: check for stdin
            arg_book_name = arguments['<book_repo_name>']
            clone(arg_book_name)
            
        elif arguments['apply']:
            arg_book_name = arguments['<book_repo_name>']
            arg_action = arguments['<action>']
            action = getattr(actions, arg_action)
            action(arg_book_name)
            
            
    except config.NotConfigured as e:
        print("\tGitberg needs configuration.")
        config.check_config()
