#! /usr/bin/env python
##########################################################################
# pysphinxdoc - Copyright (C) AGrigis, 2016
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################

# System import
from __future__ import print_function
import os
from setuptools import find_packages
import argparse

# Pysphinxdoc import
from pysphinxdoc.docgen import DocHelperWriter
from pysphinxdoc.info import long_description


# Get the module name passed in argument
def is_directory(dirarg):
    """ Type for argparse - checks that directory exists.
    """
    if not os.path.isdir(dirarg):
        raise argparse.ArgumentError(
            "The directory '{0}' does not exist!".format(dirarg))
    return dirarg
parser = argparse.ArgumentParser(description=long_description)
parser.add_argument(
    "-v", "--verbose", dest="verbose", type=int, default=0, choices=[0, 1, 2],
    help="increase the verbosity level: 0 silent, [1, 2] verbose.")
parser.add_argument(
    "-p", "--path_module", dest="path_module", required=True, metavar="PATH",
    help="the path to the module to be documented.", type=is_directory)
parser.add_argument(
    "-n", "--name_module", dest="name_module", required=True,
    help="the name of the module to be documented.")
parser.add_argument(
    "-o", "--outdir", dest="outdir", required=True, metavar="PATH",
    help="the path to write documentation.", type=is_directory)
args = parser.parse_args()

# Check that a '$name_module/doc/source' folder has been created in the project
srcdir = os.path.join(args.path_module, "doc", "source")
if not os.path.isdir(srcdir):
    raise IOError("'{0}' is not a valid directory.".format(srcdir))

# Get all the modules involved
module_names = find_packages(args.path_module)
if args.verbose > 0:
    print("[info] Documenting package {0} ...".format(args.name_module))
    print("[info] Modules to be documented: ")
    print("[info] {0}".format(module_names))

# Generate a sphinx layout, API documentation, and Sphinx configuration.
docwriter = DocHelperWriter(args.path_module, args.outdir, module_names,
                            args.name_module, verbose=args.verbose)
docwriter.write_sphinx_config()
docwriter.write_layout()
docwriter.write_index()
docwriter.write_installation()
docwriter.write_documentation_index()
docwriter.write_api_docs()
