import yaml


def generate_rke_yaml(ips, user, ssh_private_key):
    """
    Make the YAML file that RKE is going to use to create the kubernetes cluster
    :param ips: What IP addresses are we working with? Array of strings
    :param user: What user should we create?
    :param ssh_private_key: Private key text (utf-8) to include in yaml
    :return: string with the formatted yaml in it
    """
    nodes = []
    for ip in ips:
        nodes.append(
            {
                'address': ip,
                'user': user,
                'ssh_key': ssh_private_key,
                'role': [],
            },
        )
    for i, role in enumerate(['controlplane', 'etcd']):
        node_idx = i % len(nodes)
        nodes[node_idx]['role'].append(role)

    for node in nodes:
        if len(node['role']) == 0:
            node['role'].append('worker')

    worker_count = 0
    for node in nodes:
        if 'worker' in node['role']:
            worker_count += 1

    if worker_count == 0:
        for node in nodes:
            if 'controlplane' not in node['role']:
                node['role'].append('worker')
                worker_count += 1
    if worker_count == 0:
        nodes[0]['role'].append('worker')

    etcd_count = 0
    for node in nodes:
        if 'etcd' in node['role']:
            etcd_count += 1
    if etcd_count < 3:
        for node in nodes:
            if 'etcd' not in node['role'] and 'controlplane' not in node['role']:
                node['role'].append('etcd')
                etcd_count += 1
                if etcd_count >= 3:
                    break

    services = {
        'etcd': {'image': 'quay.io/coreos/etcd:latest'},
        'kube-api': {'image': 'rancher/k8s:v1.11.6-rancher2'},
        'kube-controller': {'image': 'rancher/k8s:v1.11.6-rancher2'},
        'scheduler': {'image': 'rancher/k8s:v1.11.6-rancher2'},
        'kubelet': {'image': 'rancher/k8s:v1.11.6-rancher2'},
        'kubeproxy': {'image': 'rancher/k8s:v1.11.6-rancher2'},
    }
    addons = [
        {
            "apiVersion": "v1",
            "kind": "ServiceAccount",
            "metadata": {
                "name": "cloudbolt-admin",
                "namespace": "kube-system"
            }
        },
        {
            "apiVersion": "rbac.authorization.k8s.io/v1",
            "kind": "ClusterRoleBinding",
            "metadata": {
                "name": "cloudbolt-admin"
            },
            "roleRef": {
                "apiGroup": "rbac.authorization.k8s.io",
                "kind": "ClusterRole",
                "name": "cluster-admin"
            },
            "subjects": [
                {
                    "kind": "ServiceAccount",
                    "name": "cloudbolt-admin",
                    "namespace": "kube-system"
                }
            ]
        },
    ]

    document = {
        'nodes': nodes,
        'services': services,
        'addons': '---\n' + yaml.dump_all(addons),
    }

    return yaml.dump(document)