import os, json

from .constants import (
    DEFAULT_SHOW_INDEX_EPISODE_DIGITS,
    DEFAULT_SHOW_INDEX_SEASON_DIGITS,
    DEFAULT_SHOW_INDICATOR_EPISODE_DIGITS,
    DEFAULT_SHOW_INDICATOR_SEASON_DIGITS,
)

class ConfigurationController():

    CONFIG_FILENAME = 'ffx.json'
    DATABASE_FILENAME = 'ffx.db'
    LOG_FILENAME = 'ffx.log'

    DATABASE_PATH_CONFIG_KEY = 'databasePath'
    LOG_DIRECTORY_CONFIG_KEY = 'logDirectory'
    SUBTITLES_DIRECTORY_CONFIG_KEY = 'subtitlesDirectory'
    OUTPUT_FILENAME_TEMPLATE_KEY = 'outputFilenameTemplate'
    DEFAULT_INDEX_SEASON_DIGITS_CONFIG_KEY = 'defaultIndexSeasonDigits'
    DEFAULT_INDEX_EPISODE_DIGITS_CONFIG_KEY = 'defaultIndexEpisodeDigits'
    DEFAULT_INDICATOR_SEASON_DIGITS_CONFIG_KEY = 'defaultIndicatorSeasonDigits'
    DEFAULT_INDICATOR_EPISODE_DIGITS_CONFIG_KEY = 'defaultIndicatorEpisodeDigits'


    def __init__(self):

        self.__homeDir = os.path.expanduser("~")
        self.__localVarDir = os.path.join(self.__homeDir, '.local', 'var')
        self.__localEtcDir = os.path.join(self.__homeDir, '.local', 'etc')

        self.__configurationData = {}

        # .local/etc/ffx.json
        self.__configFilePath = os.path.join(self.__localEtcDir, ConfigurationController.CONFIG_FILENAME)
        if os.path.isfile(self.__configFilePath):
            with open(self.__configFilePath, 'r') as configurationFile:
                self.__configurationData = json.load(configurationFile)

        if ConfigurationController.DATABASE_PATH_CONFIG_KEY in self.__configurationData.keys():
            self.__databaseFilePath = self.__configurationData[ConfigurationController.DATABASE_PATH_CONFIG_KEY]
            os.makedirs(os.path.dirname(self.__databaseFilePath), exist_ok=True)
        else:
            ffxVarDir = os.path.join(self.__localVarDir, 'ffx')
            os.makedirs(ffxVarDir, exist_ok=True)
            self.__databaseFilePath = os.path.join(ffxVarDir, ConfigurationController.DATABASE_FILENAME)

        if ConfigurationController.LOG_DIRECTORY_CONFIG_KEY in self.__configurationData.keys():
            self.__logDir = self.__configurationData[ConfigurationController.LOG_DIRECTORY_CONFIG_KEY]
        else:
            self.__logDir = os.path.join(self.__localVarDir, 'log')
            os.makedirs(self.__logDir, exist_ok=True)


    def getHomeDirectory(self):
        return self.__homeDir

    def getLogFilePath(self):
        return os.path.join(self.__logDir, ConfigurationController.LOG_FILENAME)

    def getDatabaseFilePath(self):
        return self.__databaseFilePath

    def getSubtitlesDirectoryPath(self):
        subtitlesDirectory = self.__configurationData.get(
            ConfigurationController.SUBTITLES_DIRECTORY_CONFIG_KEY,
            '',
        )
        return os.path.expanduser(str(subtitlesDirectory)) if subtitlesDirectory else ''

    @classmethod
    def getConfiguredIntegerValue(cls, configurationData: dict, configKey: str, defaultValue: int) -> int:
        configuredValue = configurationData.get(configKey, defaultValue)
        try:
            return int(configuredValue)
        except (TypeError, ValueError):
            return int(defaultValue)

    def getDefaultIndexSeasonDigits(self):
        return ConfigurationController.getConfiguredIntegerValue(
            self.__configurationData,
            ConfigurationController.DEFAULT_INDEX_SEASON_DIGITS_CONFIG_KEY,
            DEFAULT_SHOW_INDEX_SEASON_DIGITS,
        )

    def getDefaultIndexEpisodeDigits(self):
        return ConfigurationController.getConfiguredIntegerValue(
            self.__configurationData,
            ConfigurationController.DEFAULT_INDEX_EPISODE_DIGITS_CONFIG_KEY,
            DEFAULT_SHOW_INDEX_EPISODE_DIGITS,
        )

    def getDefaultIndicatorSeasonDigits(self):
        return ConfigurationController.getConfiguredIntegerValue(
            self.__configurationData,
            ConfigurationController.DEFAULT_INDICATOR_SEASON_DIGITS_CONFIG_KEY,
            DEFAULT_SHOW_INDICATOR_SEASON_DIGITS,
        )

    def getDefaultIndicatorEpisodeDigits(self):
        return ConfigurationController.getConfiguredIntegerValue(
            self.__configurationData,
            ConfigurationController.DEFAULT_INDICATOR_EPISODE_DIGITS_CONFIG_KEY,
            DEFAULT_SHOW_INDICATOR_EPISODE_DIGITS,
        )

    def getData(self):
        return self.__configurationData
    
    
#     
# 
# 
#     def addPattern(self, patternDescriptor):
# 
#         try:
# 
#             s = self.Session()
#             q = s.query(Pattern).filter(Pattern.show_id == int(patternDescriptor['show_id']),
#                                         Pattern.pattern == str(patternDescriptor['pattern']))
# 
#             if not q.count():
#                 pattern = Pattern(show_id = int(patternDescriptor['show_id']),
#                                     pattern = str(patternDescriptor['pattern']))
#                 s.add(pattern)
#                 s.commit()
#                 return pattern.getId()
#             else:
#                 return 0
# 
#         except Exception as ex:
#             raise click.ClickException(f"PatternController.addPattern(): {repr(ex)}")
#         finally:
#             s.close()
# 
# 
#     def updatePattern(self, patternId, patternDescriptor):
# 
#         try:
#             s = self.Session()
#             q = s.query(Pattern).filter(Pattern.id == int(patternId))
# 
#             if q.count():
# 
#                 pattern = q.first()
# 
#                 pattern.show_id = int(patternDescriptor['show_id'])
#                 pattern.pattern = str(patternDescriptor['pattern'])
# 
#                 s.commit()
#                 return True
# 
#             else:
#                 return False
# 
#         except Exception as ex:
#             raise click.ClickException(f"PatternController.updatePattern(): {repr(ex)}")
#         finally:
#             s.close()
# 
# 
# 
#     def findPattern(self, patternDescriptor):
#         
#         try:
#             s = self.Session()
#             q = s.query(Pattern).filter(Pattern.show_id == int(patternDescriptor['show_id']), Pattern.pattern == str(patternDescriptor['pattern']))
# 
#             if q.count():
#                 pattern = q.first()
#                 return int(pattern.id)
#             else:
#                 return None
# 
#         except Exception as ex:
#             raise click.ClickException(f"PatternController.findPattern(): {repr(ex)}")
#         finally:
#             s.close()
# 
# 
#     def getPattern(self, patternId : int):
# 
#         if type(patternId) is not int:
#             raise ValueError(f"PatternController.getPattern(): Argument patternId is required to be of type int")
# 
#         try:
#             s = self.Session()
#             q = s.query(Pattern).filter(Pattern.id == int(patternId))
# 
#             return q.first() if q.count() else None
# 
#         except Exception as ex:
#             raise click.ClickException(f"PatternController.getPattern(): {repr(ex)}")
#         finally:
#             s.close()
# 
