#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
OpenAccess_EPUB

Usage:
  oaepub [--version | --help] [options] COMMAND [ARGS ...]

Options:
  -h --help        show this help message and exit
  -v --version     show program version and exit
  -V --verbose     print additional information about command execution

The available commands are:
  batch       Convert all the contents of a directory to individual EPUB
  clearcache  Delete some, or all, of the contents of OpenAccess_EPUB's cache
  collection  Convert multiple articles into a single omnibus EPUB
  configure   Configure some settings for your OpenAccess_EPUB install
  convert     Convert explicit input(s) individually to EPUB
  epubzip     Zip an unzipped EPUB file back into a valid EPUB
  publishers  Show which publishers are currently supported by OpenAccess_EPUB
  validate    Validate article XML files according to their specification

See 'oaepub COMMAND --help' for more information on a specific command.

For more help, visit the documentation:
http://openaccess-epub.readthedocs.org
"""

#Standard Library modules
import sys
import logging
from importlib import import_module

#Non-Standard Library modules
from docopt import docopt

#OpenAccess_EPUB modules
from openaccess_epub._version import __version__


if __name__ == '__main__':
    args = docopt(__doc__,
                  version='OpenAccess_EPUB v.' + __version__,
                  options_first=True)

    log = logging.getLogger()

    def printverbose(info):
        if args['--verbose']:
            print(info)

    #Let's shape what gets passed along to the subcommands
    argv = []

    #If we want to pass an ubercommand option to a subcommand, do it now because
    #options are first, and like so:
    #if args['--verbose']:
    #    argv.append('--verbose')  # this would pass --verbose onward
    #argv += ['--verbose'] if args['--verbose'] else argv  # Concise, one-liner

    #Add on all of the ARGS ...  (mixture of options and args for sub-parsing)
    argv += args['ARGS']

    #This is not just to be cute, it's also a test of terminal UTF-8
    if args['COMMAND'] == 'haiku':
        sys.exit('''
A field of cotton--
as if the moon
had flowered.

- Matsuo Bashō (松尾 芭蕉)''')

    elif args['COMMAND'] == 'publishers':
        sys.exit('''\
PLoS      - http://www.plos.org/
Frontiers - http://www.frontiersin.org/''')

    #Decide which subcommand to run based on args['COMMAND']
    else:
        try:
            mod = import_module('openaccess_epub.commands.' + args['COMMAND'])
        except ImportError:
            sys.exit('Your command \'{0}\' was not recognized'.format(args['COMMAND']))
        else:
            main = mod.main
            printverbose('''\
Running {cmd} command with the following options/arguments:
{args}

{cmd} command script located at:
{filename}'''.format(cmd=args['COMMAND'], args=str(argv), filename=mod.__file__))
            main(argv=argv)
