"""Generate the default-config file in the documentation."""

import sys
from subprocess import Popen, PIPE

DEFAULT_CONFIG = 'docs/source/default-config.rst'
INDENT = ' '
MAX_LENGTH = 82
HEADER = """\
.. File generated by tools/gendoc_default_config.py.
   DO NOT EDIT THIS FILE DIRECTLY.

.. _default_config:

Built-in Default Configuration
==============================

As printed by the command ``pa-dlna --dump-default``.

::

"""

def wrap(line, max=MAX_LENGTH):
    """This generator recursively wraps 'line', yielding its parts.

    Splitting 'line' at word boundaries.
    """

    length = len(line)
    if length <= max:
        if length:
            yield line.rstrip()
        return

    if line[max-1].isspace() or line[max].isspace():
        length = max
    else:
        idx = line[:max].rfind(' ')
        if idx != -1:
            length = idx
        else:
            length = len(line)

    yield line[:length].rstrip()
    yield from wrap(line[length:].lstrip())

def main():
    try:
        with open(DEFAULT_CONFIG, 'w') as f:
            f.write(HEADER)
            with Popen([sys.executable, '-m', 'pa_dlna.pa_dlna',
                        '--dump-default'], stdout=PIPE) as proc:
                for line in proc.stdout:
                    line = line.decode()
                    line = line.replace('\t', '    ').rstrip()
                    if line:
                        for part in wrap(line):
                            f.write(INDENT + part + '\n')
                    else:
                        f.write('\n')
    except FileNotFoundError as e:
        print(f'{e!r}: {DEFAULT_CONFIG}',
              file=sys.stderr)
        sys.exit(1)
    print(f"A new '{DEFAULT_CONFIG}' file has been written.")

if __name__ == '__main__':
    main()
