# _directory_creator.py
#
# Project: AutoArchive
# License: GNU GPLv3
#
# Copyright (C) 2003 - 2025 Róbert Čerňanský



import os

from AutoArchive._infrastructure.configuration import ConfigurationBase, Options
from AutoArchive._infrastructure.configuration.config_dir import ConfigDir
from AutoArchive._infrastructure.utils import ErrorHandling



class DirectoryCreator:

    def __init__(self, configuration: ConfigurationBase):
        self.__configuration = configuration



    def createUserConfigSpace(self):
        userDirectoryCreated = ConfigDir(
            self.__configuration[Options.USER_CONFIG_DIR]).createIfNotExists(self.__configuration)
        self.__createArchiveSpecsDirectory(userDirectoryCreated)



    def __createArchiveSpecsDirectory(self, userDirectoryCreated):
        userConfigDir = self.__configuration[Options.USER_CONFIG_DIR]
        archiveSpecsDirectory = self.__configuration[Options.ARCHIVE_SPECS_DIR]
        if not os.path.exists(archiveSpecsDirectory):
            try:

                # show warning only if we are not quiet and if the user configuration directory was not just created;
                # or in case it was just created the archive specifications directory is not its subdirectory
                if not self.__configuration[Options.QUIET] and \
                   (not userDirectoryCreated or
                    not os.path.commonprefix((userConfigDir, archiveSpecsDirectory)) == userConfigDir):

                    ErrorHandling.printWarning(str.format(
                            "Archive specifications directory does not exists. Creating \"{}\".",
                            archiveSpecsDirectory))

                os.makedirs(archiveSpecsDirectory)

            except OSError as ex:
                ErrorHandling.printError(str.format(
                        "Unable to create archive specifications directory: \"{}\". The reason is: {}",
                        archiveSpecsDirectory, ex.strerror))
