from __future__ import absolute_import
from __future__ import division

from collections import OrderedDict
import logging

from vdsm.common import dsaversion
from vdsm.common import fileutils

DNS_CONF_FILE = '/etc/resolv.conf'
DNS_NAMESERVER = 'nameserver'
MAX_DNS_PER_HOST = 3


def get_host_nameservers():
    try:
        with open(DNS_CONF_FILE, 'r') as file_object:
            file_text = file_object.read()
    except IOError as e:
        logging.warning('Failed to read {}: {}'.format(DNS_CONF_FILE, e))
        return []
    return _parse_nameservers(file_text)


def add_host_nameservers(servers):
    nameservers = servers + get_host_nameservers()
    nameservers = list(OrderedDict.fromkeys(nameservers).keys())
    _set_host_nameservers(nameservers[:MAX_DNS_PER_HOST])


def _set_host_nameservers(servers):
    with fileutils.atomic_file_write(DNS_CONF_FILE, 'w') as file_object:
        file_object.write(CONFFILE_HEADER_SIGNATURE + ' ' +
                          dsaversion.raw_version_revision + '\n')
        nameservers = '\n'.join(
            ['{} {}'.format(DNS_NAMESERVER, server) for server in servers])
        file_object.write(nameservers)


def _parse_nameservers(file_text):
    nameservers = []
    for line in file_text.splitlines():
        words = line.strip().split()
        if len(words) < 2:
            continue
        if words[0] == 'nameserver':
            nameservers.append(words[1])
    return nameservers
