import configparser
from . import util
import os


class BenchmarkConfig:
    """
    Generic configuration storage and parser.
    """

    def __init__(self):
        self.config_ = configparser.ConfigParser()

    def readFromFile(self, filename):
        """
        Read configuration from given file. File name is expected to be
        a full file path to read from.

        Will do nothing if file does not exist.
        """
        if os.path.exists(filename):
            return self.config_.read(filename)
        return []

    def readGlobalConfig(self, name):
        """
        Read named configuration from benchmark's configuration folder
        """
        config_dir = util.getGlobalConfigDirectory()
        filename = os.path.join(config_dir, name + ".cfg")
        return self.readFromFile(filename)

    def dump(self):
        """
        Dump configuration to screen for debugging purposes.
        """
        for section_name in self.config_.sections():
            section = self.config_[section_name]
            print("[{}]" . format(section_name))
            for key, value in section.items():
                print("{} = {} " . format(key, value))

    # Bypass some handy methods to underlying configuration object.

    def sections(self):
        return self.config_.sections()

    def __getitem__(self, key):
        return self.config_.__getitem__(key)

    def __setitem__(self, key, value):
        return self.config_.__setitem__(key, value)
