# vim: ft=python fileencoding=utf-8 sw=4 et sts=4

# This file is part of vimiv.
# Copyright 2017-2023 Christian Karl (karlch) <karlch at protonmail dot com>
# License: GNU GPL v3, see the "LICENSE" and "AUTHORS" files for details.

"""Utility functions to create reST files."""


class RSTFile:
    """Context manager wrapping a file and adding rst utility methods."""

    def __init__(self, filename):
        self._file = open(filename, "w", encoding="utf-8")
        self._write_header()

    def __enter__(self):
        return self

    def __exit__(self, _type, _value, _traceback):
        self._file.close()

    def write(self, text):
        """Write text directly to the file."""
        self._file.write(text)

    def write_section(self, title):
        """Write top-level section title to file."""
        self.write("#" * len(title) + "\n")
        self.write(title + "\n")
        self.write("#" * len(title) + "\n\n")

    def write_subsection(self, title):
        """Write sub-section title to file."""
        self.write(title + "\n")
        self.write("*" * len(title) + "\n\n")

    def write_subsubsection(self, title):
        """Write subsub-section title to file."""
        self.write(title + "\n")
        self.write("=" * len(title) + "\n\n")

    def write_table(self, rows, title="", widths="auto"):
        """Write reST table to file.

        Currently only tables with 2 columns are supported.

        Args:
            rows: List of tuples containing the columns. First row is the header.
            title: Title of the table.
        """
        # Find out size of first column
        ncols = len(rows[0])
        lengths = [max([len(elem[i]) for elem in rows]) for i in range(ncols)]
        empty_row = ["=" * n for n in lengths]

        def format_row(row=empty_row):
            parts = " ".join(f"{elem:{n}s}" for elem, n in zip(row, lengths))
            return f"   {parts}\n"

        # Header
        self.write(f".. table:: {title}\n   :widths: {widths}\n\n")
        self.write(format_row())
        self.write(format_row(rows[0]))
        self.write(format_row())
        # Content
        for row in rows[1:]:
            self.write(format_row(row))
        # Footer
        self.write(format_row())

    def _write_header(self):
        """Write header to file explaining that the file was autogenerated."""
        self.write(
            ".. This file was autogenerated by scripts/src2rst.py.\n"
            "   The extension .rstsrc is used to avoid sphinx copying this "
            "file directly.\n   Do not edit by hand.\n\n"
        )
