#!/usr/bin/env python3
#
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018  Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Timeline is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Timeline.  If not, see <http://www.gnu.org/licenses/>.


import sys
import os


INDEX_TEMPLATE = """\
Welcome to the Timeline documentation!
========================================

Timeline is a cross-platform application for displaying and navigating events on a timeline.

.. toctree::
   :maxdepth: 1
   :caption: Entry point:

   timeline
   
.. toctree::
   :maxdepth: 1
   :caption: Code:
   
   timelinelib

.. toctree::
   :maxdepth: 1
   :caption: Tests:
   
   unit


Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
"""

PACKAGE_TEMPLATE = """\
package *$package-name$*
==========================================================================
 
.. automodule:: $package-name$
   :members:
 
.. toctree::
   :maxdepth: 1
   :caption: Modules:
 
   $modules-list$
 
.. toctree::
   :maxdepth: 1
   :caption: Subpackages:
 
   $packages-list$
"""


MODULE_TEMPLATE = """\
module *$module-name$*
====================================================================================================

.. automodule:: $module-name$
    :members:
"""


def create():
    try:
        verify_arguments()
        create_rst_files('source')
        create_rst_files('test')
    except TypeError:
        pass


def verify_arguments():
    if len(sys.argv[1:]) != 2:
        display_error(f"Wrong number of arguments. Expected 2, Got {len(sys.argv[1:])} ")
        raise TypeError()
    input_path = sys.argv[1]
    if not os.path.exists(input_path):
        display_error(f"Can't find input path: {input_path}")
        raise TypeError()
    output_path = sys.argv[2]
    if not os.path.exists(output_path):
        display_error(f"Can't find output path: {output_path}")
        raise TypeError()


def display_error(message):
    """
    Usage:    python create_indexes_rst_files.py  input-path  output-path

      input-path:   source directory to investigate
      output-path:  directory in which the result is to be placed
    """
    print(message)
    print(display_error.__doc__)


def create_rst_files(subdir):
    create_index_rst()
    input_path = os.path.join(sys.argv[1], subdir)
    output_path = sys.argv[2]
    print(f'{input_path}{os.sep}specs')
    for dirpath, dirnames, filenames in os.walk(input_path):
        if '__pycache__' not in dirpath:
            path = os.path.abspath(dirpath)
            path = path[len(os.path.abspath(input_path)) + 1:]
            modules = []
            if (not dirpath.startswith(f'{input_path}{os.sep}build')
                and not dirpath.startswith(f'{input_path}{os.sep}dist')
                and not dirpath.startswith(f'{input_path}{os.sep}autopilot')
                and not dirpath.startswith(f'{input_path}{os.sep}lint')
                and not dirpath.startswith(f'{input_path}{os.sep}specs')):
                    for filename in filenames:
                        if filename.endswith('.py') and filename != '__init__.py':
                            if path == '':
                                fn = f"{filename}".replace('.py', '.rst')
                            else:
                                fn = f"{path.replace(os.sep, '_')}_{filename}".replace('.py', '.rst')
                            modules.append(fn.replace('.rst', ''))
                            with open(os.path.join(output_path, fn), 'w') as f:
                                if path == '':
                                    module_name = filename.replace('.py', '')
                                else:
                                    module_name = f"{path.replace(os.sep, '.')}.{filename.replace('.py', '')}"
                                print(f'Module name: {module_name}')
                                if module_name == 'timelinelib.test.coptic_utils':
                                    a = 1
                                f.write(MODULE_TEMPLATE.replace('$module-name$', module_name))
            packages = []
            if not dirpath.startswith(f'{input_path}{os.sep}build') and not dirpath.endswith(f'{input_path}{os.sep}dist'):
                for dirname in dirnames:
                    if dirname != '__pycache__':
                        if path == '':
                            filename = f"{dirname}"
                        else:
                            filename = f"{path.replace(os.sep, '_')}_{dirname}"
                        packages.append(filename)
                if (path != ''
                        and not dirpath.startswith(f'{input_path}{os.sep}build')
                        and not dirpath.startswith(f'{input_path}{os.sep}dist')
                        and not dirpath.startswith(f'{input_path}{os.sep}autopilot')
                        and not dirpath.startswith(f'{input_path}{os.sep}lint')
                        and not dirpath.startswith(f'{input_path}{os.sep}specs')):
                    filename = f"{path}".replace(os.sep, '_')
                    with open(os.path.join(output_path, filename + '.rst'), 'w') as f:
                        f.write(PACKAGE_TEMPLATE
                                .replace('$package-name$', filename)
                                .replace('_', '.')
                                .replace('$modules-list$', '\n   '.join(modules))
                                .replace('$packages-list$', '\n   '.join(packages)))

def create_index_rst():
    output_path = sys.argv[2]
    index_path = os.path.join(output_path, 'index.rst')
    with open(index_path, 'w') as f:
        f.write(INDEX_TEMPLATE)


if __name__ == "__main__":
    create()
