# -*- coding: utf-8 -*-

"""Helper for /etc/hosts in LXC containers
"""

from sys import stderr

def _gen_crossed_hosts(fqdns, ips):
    """Associate each data:`ip` to each data:`fqdn`.

    :param fqdns: FQDNS of hosts
    :type fqdns: `list` of `str`
    :param ips: IPs of hosts
    :type ips: `list` of `str`
    :return: structured view of /etc/hosts entries
    :rtype: `list` of `dict`

    """
    hosts = []
    for ip in ips:
        if ip is None:
            continue

        for fqdn in fqdns:
            if fqdn is None:
                continue

            short_name = ''
            if '.' in fqdn:
                short_name = fqdn.split('.')[0]

            hosts.append({u'hostname': short_name,
                          u'fqdn': fqdn,
                          u'ip': ip})

    return hosts


def _gen_hosts(fqdns, ips):
    """Associate one :data:`ip` per :data:`fqdn`.

    :param fqdns: FQDNS of hosts
    :type fqdns: `list` of `str`
    :param ips: IPs of hosts
    :type ips: `list` of `str`
    :return: structured view of /etc/hosts entries
    :rtype: `list` of `dict`

    """
    hosts = []
    for idx, fqdn in enumerate(fqdns):
        short_name = ''

        if '.' in fqdn:
            short_name = fqdn.split('.')[0]

        hosts.append({u'fqdn': fqdn,
                      u'hostname': short_name,
                      u'ip':ips[idx]})

    return hosts


def get_etc_hosts(container, local_domain):
    """Get /etc/hosts informations.

    :param container: container informations
    :type container: `dict`
    :param local_domain: local domain name
    :type local_domain: `str`
    :return: hosts descriptions
    :rtype: `list` of `dict`

    """
    hosts = []
    # Name for all interfaces IPs
    ifs = []
    for interface in container[u'interfaces']:
        if interface.get(u'ip', None) is None:
            continue
        ifs.append({u'hostname': container[u'name'],
                    u'fqdn': u'{0}.{1}'.format(container[u'name'],
                                               local_domain),
                    u'ip': interface[u'ip']})

    if len(ifs) > 0:
        ifs[0].update({u'comment': u'# Container interfaces'})

    hosts.extend(ifs)

    for host in container[u'hosts']:
        host_list = []
        if not host.get(u'activate', False):
            continue

        fqdns = host.get(u'name', None)
        ips = host.get(u'ip', None)

        if fqdns is None or ips is None:
            continue

        # Make sure to have lists
        if not isinstance(fqdns, list):
            fqdns = [fqdns]

        if not isinstance(ips, list):
            ips = [ips]

        if host.get(u'crossed', True):
            host_list = _gen_crossed_hosts(fqdns, ips)
        else:
            if len(fqdns) != len(ips):
                msg = u"Warning: use crossed associtation: host name list length missmatch IP list length in container {0}:\n"
                stderr.write(msg.format(host[u'container']))
                stderr.write("Host names: {0}\n".format(fqdns))
                stderr.write("Host IPs: {0}\n".format(ips))
                host_list = _gen_crossed_hosts(fqdns, ips)
            else:
                host_list = _gen_hosts(fqdns, ips)

        if len(host_list) > 0 and host.get(u'comment', None) is not None:
            # Add the comment after an empty line
            host_list[0].update({u'comment': '\n# {0}'.format(host[u'comment'])})
        elif len(host_list) > 0:
            # Separate blocs with one empty line
            host_list[0].update({u'comment': ''})

        hosts.extend(host_list)

    return hosts
