# coding: utf-8

import random


def sort_hosts(dcs, current_dc, db_hosts):
    """
    :param dcs: mapping DC to a list of other DCs in a preferred order
    :param current_dc: current instance DC
    :param db_hosts: list of hosts as returned by `yc mdb cluster ListHosts --projectId 33e2f33c-da0a-4de1-9936-8bc269a0d301`
    :return: comma-separated list of hosts
    """
    try:
        preferred = dcs[current_dc]
    except KeyError:
        # Use random order when the current DC is unknown or undefined
        preferred = list(dcs.keys())
        random.shuffle(preferred)
    # Map DCs to ranks. The less the more preferred.
    dc_ranks = {dc: rank for rank, dc in enumerate(preferred)}
    # List of (host, geo) pairs.
    # `geo` is set to None if undefined.
    hosts = [
        (host['name'], host.get('options', {}).get('geo')) for host in db_hosts
    ]
    # Sort hosts by ranks of their DCs.
    # Use random ranks when a host DC is unknown or undefined
    hosts.sort(
        key=lambda x: dc_ranks.get(x[1], random.randrange(0, len(dcs) + 1))
    )
    return ','.join(host for host, geo in hosts)


def create_profile(host_string, config, profile_type, user, password):
    assert profile_type in ('read-write', 'any')
    atomic = (profile_type == 'read-write')
    return {
        'ENGINE': 'idm.framework.backend',
        'HOST': host_string,
        'PORT': config.pg_port,
        'USER': user,
        'PASSWORD': password,
        'NAME': config.pg_name,
        'DISABLE_SERVER_SIDE_CURSORS': True,
        'ATOMIC_REQUESTS': atomic,
        'CONN_MAX_AGE': 15 * 60,  # 15 minutes
        'OPTIONS': {
            'connect_timeout': 5,
            'sslmode': 'verify-full',
            'sslrootcert': '/etc/ssl/certs/ca-certificates.crt',
            'target_session_attrs': profile_type
        },
    }
