import pathlib


class RootDocumenter:
    """
    A basic root documenter.

    This documenter generates only one reStructuredText document: the root API
    index page, which contains information about all of the modules traversed
    by an :py:class:`~uqbar.apis.APIBuilder`.

    Output is a basic `toctree` directive.

    ::

        >>> import uqbar.apis
        >>> documenter = uqbar.apis.RootDocumenter(
        ...     module_documenters=[
        ...         uqbar.apis.ModuleDocumenter('uqbar.io'),
        ...         uqbar.apis.ModuleDocumenter('uqbar.strings'),
        ...         ],
        ...     )
        >>> print(str(documenter))
        API
        ===
        <BLANKLINE>
        .. toctree::
        <BLANKLINE>
           uqbar/io/index
           uqbar/strings
        <BLANKLINE>

    .. tip::

       Subclass :py:class:`~uqbar.apis.RootDocumenter` to
       implement your own custom module documentation output.
       You'll need to provide your desired reStructuredText output
       via an overridden
       :py:meth:`~uqbar.apis.RootDocumenter.RootDocumenter.__str__`
       implementation.

       See :py:class:`~uqbar.apis.SummarizingRootDocumenter` for an example.

    :param module_documenters: a list of of documenters for modules and
        packages of the root documenter; these are generated by an
        :py:class:`~uqbar.apis.APIBuilder` instance rather than the module
        documenter directly
    """

    ### CLASS VARIABLES ###

    __documentation_section__ = 'Documenters'

    ### INITIALIZER ###

    def __init__(self, module_documenters=None, title='API'):
        import uqbar.apis
        if module_documenters is not None:
            assert all(isinstance(_, uqbar.apis.ModuleDocumenter)
                for _ in module_documenters), module_documenters
            module_documenters = tuple(module_documenters)
        self._module_documenters = module_documenters or ()
        self._title = title

    ### SPECIAL METHODS ###

    def __str__(self):
        result = [self.title, '=' * len(self.title), '']
        if self.module_documenters:
            result.extend(['.. toctree::', ''])
            for module_documenter in self.module_documenters:
                path = module_documenter.package_path.replace('.', '/')
                if module_documenter.is_package:
                    path = '{}/index'.format(path)
                result.append('   {}'.format(path))
            result.append('')
        return '\n'.join(result)

    ### PUBLIC PROPERTIES ###

    @property
    def documentation_path(self):
        return pathlib.Path('index.rst')

    @property
    def module_documenters(self):
        return self._module_documenters

    @property
    def title(self):
        return self._title
