from TexSoup import TexNode
from pathlib import Path


class TeXWriter():
    def __init__(self) -> None:
        pass

    def write(self, soup: TexNode, output: str, file_only: bool, force: bool) -> None:
        path = self._get_verified_output_path(output, file_only, force)
        with open(path, 'w') as f:
            f.write(str(soup))

    def _get_verified_output_path(self, output: str, file_only: bool, force: bool) -> Path:
        path = Path(output)
        if path.suffix and path.suffix != '.tex':
            raise ValueError(f"Cannot write to suffix {path.suffix}")
        elif not path.suffix and file_only:
            path = path.with_suffix(".tex")

        if not file_only:
            path = path.with_suffix('') / path.name
            self._create_directory(path.parent)

        file_path = path.with_suffix(".tex")
        if file_path.exists() and not force:
            raise FileExistsError(
                "Output .tex file already exists. You can overwrite using --force.")
        return file_path

    def _create_directory(self, dir_path: Path):
        dir_path.mkdir(exist_ok=True, parents=True)
