from configparser import ConfigParser
class ChartConfig:
    """
    Class that holds the chart section of a configuration file (for an instrument).
    
    Attributes :
        chart_config (Section) : the Section corresponding to the "chart" section in the given configuration file
    """
    def __init__(self, path):
        """
        Parameters :
            path (str) : the path to the configuration file
        """
        cfgp = ConfigParser(interpolation=None)
        cfgp.read(path)
        self.chart_config = cfgp["chart"]

    def get_variable_parameter_config(self, key):
        """
        Gets the configuration of the given key in the configuration file (chart section).

        Parameters :
            key (str) : the key to look for in the chart section (<variable>[.<param>])

        Returns :
            {"cat":(str), "color":(str), "unit":(str)} | None : a dictionnary representing the different options for the given key in the chart section.
                The different options are in this dict if they are found in the chart section for the given key. Returns None if the key is not in the chart section,
                or if there is a syntax problem for the given key.
        """
        config = {}
        positionnal = ["cat", "color", "unit"]
        if key in self.chart_config.keys():
            raw_value = self.chart_config[key]

            arguments = raw_value.split(",")
            keyword_mode = False
            for i, argument in enumerate(arguments):
                pieces = argument.split(":")
                if len(pieces) == 2:
                    keyword_mode = True
                    if pieces[1] != "":
                        config[pieces[0]] = pieces[1]
                else:
                    if not keyword_mode: #everything is going well
                        if pieces[0] != "":
                            config[positionnal[i]] = pieces[0]
                    else: #we cannot have a positionnal argument after a keyword argument
                        return None
            return config
        else:
            return None
