import logging
import requests
from django.http import HttpResponse, HttpRequest
from settings import NANNY_TANKS_URL, CONDUCTOR_TANKS_URL
import json


def get_tanks(request):
    """
    gets tanks from conductor and nanny
    :param request: Http request optionally
    :return: json
    [
        [
            host,
            location (dc|rtc),
            spec
        ],
        ...
    ]
    """
    tanks = get_conductor_tanks() + get_rtc_tanks()
    if isinstance(request, HttpRequest):
        return HttpResponse(json.dumps(tanks), content_type='application/json')
    else:
        return tanks  # to use from common.management.commands.tank_status


def get_conductor_tanks():
    url = CONDUCTOR_TANKS_URL
    json_resp = requests.get(url, verify=False).json()
    return json_resp


def get_rtc_tanks():
    try:
        resp = requests.get(NANNY_TANKS_URL, verify=False).json()
        result = resp['result']
        tanks_list = sorted((
            ['{}:{}'.format(tank['container_hostname'], tank['port']), 'rtc', False]
            for tank in result if 'a_topology_group-ALL_RCLOUD_TANKS' in tank.get('itags', [])
        ), key=lambda x: x[0])
    except (KeyError, IOError, TypeError):
        logging.error('Failed to get rtc tanks', exc_info=True)
        return []

    return tanks_list
