# -*- coding: utf-8 -*-
#
# This file is part of the parce Python package.
#
# Copyright © 2019-2020 by Wilbert Berendsen <info@wilbertberendsen.nl>
#
# This module 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.
#
# This module 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 this program.  If not, see <https://www.gnu.org/licenses/>.


"""
Updates the language stub files in source/lang and the listing in source/langs.inc
"""

EXAMPLES_DIRECTORY = "../tests/lang/"


import collections
import glob
import io
import os
import sys

sys.path.insert(0, "..")

import parce
from parce.language import get_all_modules, get_languages

STUB = r"""{0}
{1}

.. automodule:: parce.lang.{0}
    :members:
    :undoc-members:
    :show-inheritance:

"""

EXAMPLE_STUB = r"""

Root lexicon ``{0}`` and text:

.. code-block:: {1}

{2}

Result tree::

{3}


"""

LANGS_INC_HEADER = r"""
.. Generated by ../update_languages.py -- do not edit!

.. list-table::
   :header-rows: 1
   :widths: 20 70

   * - Module
     - Languages

"""

def indent(text, indent=4):
    """Indent text."""
    return '\n'.join(' ' * indent + line for line in text.splitlines())


def make_stub(name, examples):
    text = STUB.format(name, '=' * len(name))
    with open("source/lang/{0}.rst".format(name), "w") as f:
        f.write(text)

        if examples:
            if len(examples) > 1:
                f.write("Examples:\n---------")
            else:
                f.write("Example:\n--------")

            for root_lexicon, text in examples:
                tree = parce.root(root_lexicon, text)
                buf = io.StringIO()
                tree.dump(buf)
                f.write(EXAMPLE_STUB.format(root_lexicon, name, indent(text),
                                            indent(buf.getvalue())))


def get_examples():
    """Return a list of all example documents in tests/lang/example.*."""
    pattern = os.path.join(EXAMPLES_DIRECTORY, "example*.*")
    return glob.glob(pattern)


def main():

    # make a mapping from the example files to their Language
    all_examples = collections.defaultdict(list)
    for filename in get_examples():
        text = open(filename).read()    # TODO encoding?
        root_lexicon = parce.find(filename=filename, contents=text)
        all_examples[root_lexicon.language].append((root_lexicon, text))


    with open("source/langs.inc", "w") as f:
        f.write(LANGS_INC_HEADER)
        for name in get_all_modules():
            langs = list(get_languages(name))
            if langs:
                clss = ", ".join(":class:`~parce.lang.{0}.{1}`".format(name, lang.__name__)
                    for lang in langs)
                examples = sum((all_examples.get(lang, []) for lang in langs), [])
                make_stub(name, examples)
                f.write("   * - :mod:`~parce.lang.{0}`\n".format(name))
                f.write("     - {0}\n\n".format(clss))

if __name__ == "__main__":
    main()

