
from __future__ import absolute_import
from __future__ import division
import errno
import os

from vdsm.tool.configfile import ConfigFile

def get_file_path(fname, files):
    return files[fname]['path']


def remove_conf(files, version):
    for cfile, content in files.items():
        content['removeConf'](content['path'], version)


def add_section(content, version, vdsmConfiguration={}):
    configuration = {}
    for fragment in content['fragments']:
        if vdsmConfiguration:
            if is_applicable(fragment, vdsmConfiguration):
                configuration.update(fragment['content'])
        else:
            configuration.update(fragment['content'])
    if configuration:
        with open_config(content['path'], version) as conff:
            for key, val in configuration.items():
                conff.addEntry(key, val)


def remove_section(path, version):
    if os.path.exists(path):
        with open_config(path, version) as conff:
            conff.removeConf()


def remove_file(content, version, vdsmConfiguration):
    try:
        os.unlink(content['path'])
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise


def get_persisted_files(files):
    return [
        cfile['path'] for cfile in files.values()
        if cfile['persisted']
    ]


def open_config(path, conf_version):
    return ConfigFile(path, conf_version)


def is_applicable(fragment, vdsmConfiguration):
    applyFragment = True
    for key, booleanValue in fragment['conditions'].items():
        if vdsmConfiguration[key] != booleanValue:
            applyFragment = False
    return applyFragment
