import os
from types import NoneType
from typing import Union


class doc:
    def __init__(self,
                 autodoc: Union[str, NoneType],
                 doc_dir: str,
                 name: str) -> None:
        self.autodoc = autodoc
        self.doc_dir = doc_dir
        self.name = name
        if autodoc is not None:
            self._genReferences()

        return

    def _genReferences(self):
        text = [".. _reference:\n",
                "\n",
                "*********\n",
                "Reference\n",
                "*********\n"]
        module_names = []
        for _, _, file in os.walk(os.getcwd()+"/"+self.autodoc):
            for file in file:
                if file.endswith('.py'):
                    module_names.append(file)
        for module in module_names:
            module = module.rsplit('.')[0]
            text.append("\n")
            text.append(f".. _{module}:\n")
            text.append("\n")
            text.append(f"{module}\n")
            decorator = ""
            for char in range(len(module)):
                decorator = decorator + "="
            text.append(f"{decorator}\n")
            text.append("\n")
            text.append(f".. automodule:: {self.autodoc.replace('/', '.')}"
                        f".{module}\n")
            text.append("   :members:\n")
        with open(f"{self.doc_dir}/source/refereces.rst", "w") as f:
            f.writelines(text)

        return

    def genGettingStarted(self):
        decorator = ""
        for char in range(len(self.name)):
            decorator = decorator + "-"
        text = [".. _getting_started:\n",
                "\n",
                "***************\n",
                "Getting Started\n",
                "***************\n",
                "\n",
                f".. _{self.name}:\n",
                "\n",
                f"{self.name}\n",
                f"{decorator}\n"]
        with open(f"{self.doc_dir}/source/getting_started.rst", "w") as f:
            f.writelines(text)

        return

    def updateIndex(self):
        with open(f"{self.doc_dir}/index.rst", "r") as f:
            text = f.readlines()
        if self.autodoc is None:
            text.insert(13, "   source/getting_started.rst\n")
            text.insert(14, "\n")
        else:
            text.insert(13, "   source/getting_started.rst\n")
            text.insert(14, "   source/refereces.rst\n")
            text.insert(15, "\n")
        with open(f"{self.doc_dir}/index.rst", "w+") as f:
            f.writelines(text)

        return
