import os
import yaml

class HIDMapperConfig (object):
    """
        Configuration for HIDMapper
    """
    CONF_FILENAME = "hidmapper.conf"
    CONF_PATH_ALTERNATIVES = [
        "~/.%s" % CONF_FILENAME,
        "/etc/hidmapper/%s" % CONF_FILENAME,
        "./conf/%s" % CONF_FILENAME
    ]

    def __init__ (self, conf_file = None):
        if not conf_file:
            for i in HIDMapperConfig.CONF_PATH_ALTERNATIVES:
                if os.path.exists(i):
                    conf_file = i
                    break

        self._conf_file = conf_file
        
        # Properties in the configuration
        self._default_profile = None
        
        if self._conf_file:
            self.load()

    def load (self):
        conf = {}
        with open(self._conf_file, 'r') as f:
            conf = yaml.safe_load(f)
        if conf.get('profile'):
            self._default_profile = conf.get('profile')
        return True
    
    def save (self, save_as = None):
        """
            Save the current profile, optionally with another name
        """
        template = """### AUTOGENERATED CONFIGURATION FILE

# Profile to load when started
profile: {profile}

        """.format(profile = self._default_profile)
        
        with open(self._conf_file, 'w') as f:
            f.write(template)
        
        return True

    @property
    def default_profile (self):
        return self._default_profile
        
    @default_profile.setter
    def default_profile (self, default_profile):
        self._default_profile = default_profile
        self.save()
    
    
    