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



import os
from abc import abstractmethod, ABC

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



class AppDir(ABC):
    """Application directory

    Can be used to manage for example user configuration directory or user data directory."""

    __VERSION_FILE = ".version"



    def __init__(self, path: str):
        self.__path = path
        self.__versionFilePath = os.path.join(self.__path, self.__VERSION_FILE)



    def __str__(self):
        return self.path



    @property
    @abstractmethod
    def version(self) -> str:
        pass



    @property
    def path(self) -> str:
        return self.__path



    def createIfNotExists(self, configuration: ConfigurationBase) -> bool:
        if not os.path.exists(self.__path):
            try:
                if not configuration[Options.QUIET]:
                    ErrorHandling.printWarning(f"Directory '{self.__path}' does not exists. Creating.")
                os.makedirs(self.__path)
                self.setToCurrentVersion()
                return True
            except OSError as ex:
                ErrorHandling.printError(f"Unable to create directory: '{self.__path}'. The reason is: {ex.strerror}")

        return False



    def isCurrentVersion(self) -> bool:
        return os.path.exists(self.__versionFilePath) and self.__retrieveVersion() == self.version



    def setToCurrentVersion(self):
        with open(self.__versionFilePath, "w") as versionFile:
            versionFile.write(self.version)



    def __retrieveVersion(self) -> str:
        with open(self.__versionFilePath, "r") as versionFile:
            return versionFile.readline().strip()
