import os

class Settings:
    """Used to read and save settings for `Exporter` plugin.

    Writes and reads from file `exporter-settings`.

    Methods
    -------
    get_value(key, default)
        Gets value by `key`. Returns `default` if `key` doesn't exist in file.
    save(key, value)
        Saves a key, value pair to file.
    read()
        Reads settings file.
    merge(*dictionaries)
        Helper methods merging multiple dictionaries together.
    """

    config_file_path = os.path.abspath(os.path.dirname(__file__)) + os.path.sep + 'exporter-settings'
    """Settings file location. Set to the plugin directory currently with `exporter-settings` file."""
    
    @staticmethod
    def get_value(key, default):
        """
        Gets value of `key`.

        Gets value of `key` by first reading from the settings file and then
        indexing into it.

        Args:
            key (string): Key of setting to get.
            default (string): Default value to return if setting doesn't exist.
        
        Returns:
            Setting's value if it exists and the file is valid; `default` otherwise.
        """
        settings = Settings.read()
        if settings is not None and key in settings:
            return settings[key]

        return default

    @staticmethod
    def save(key, value):
        """
        Saves a key, value pair to settings file.

        Reads the settings file and then merges the key, value pair into it.
        The resulting dictionary is then written to disk.

        Args:
            key (string): Key representing setting.
            value (string): Value corresponding to `key`.
        """
        settings = Settings.merge(Settings.read() or {}, {key: value})
        with open(Settings.config_file_path, 'w') as settings_file:
            settings_file.writelines([key + '=' + settings[key] + '\n' for key in settings])

    @staticmethod
    def read():
        """
        Reads file.

        Checks for the config file path. Reads the values from file if it exists
        and then parses the file into a dictionary.

        Returns:
            Settings dictionary if successfully read. None otherwise.
        """
        settings = {}
        if os.path.exists(Settings.config_file_path):
            with open(Settings.config_file_path, 'r') as settings_file:
                for line in settings_file.readlines():
                    _key, val = line.rstrip('\n').split('=')
                    settings[_key] = val
        
        return settings
        
    @staticmethod
    def merge(*dicts):
        """
        Merges multiple dictionaries together.
        
        Last dictionary values replaces the ones that existed in the
        dictionaries coming before.

        Returns:
            New dictionary that's the result of the merged dictionaries.
        """
        result = {}
        for dict in dicts:
            result.update(dict)
        return result
