
from .cluster import get_cluster_data as cluster
from .caches import sla_table

from django.core.cache import cache

import json  # noqa


def is_sla_ctype(ctype):
    return 'stable' in ctype


def service_ctypes(service='', ctype=''):
    serv_ct = cache.get('service-ctypes')
    if not serv_ct:
        serv_list, serv_ct, _, err = cluster.get_services()
        if not err:
            cache.set('service-ctypes', serv_ct, 120)
        else:
            return {'success': False,
                    'error': 'cannot get services from dm: %s' % err}
    result = {'success': True, 'serv_ct': serv_ct}
    match_success = True
    match_error = ''
    if ctype and ctype not in serv_ct:
        match_success = False
        match_error = 'ctype %s not found anywhere' % ctype
    elif service and ctype and service not in serv_ct[ctype]:
        match_success = False
        ctypes_s = [ct for ct, slist in serv_ct.items() if service in slist]
        if not ctypes_s:
            match_error = 'service %s not found anywhere' % service
        else:
            match_error = 'service %s not found in ctype %s' % (service, ctype)
    elif service and not ctype:
        ctypes_s = [ct for ct, slist in serv_ct.items() if service in slist]
        ctypes_stable = [ct for ct in ctypes_s if ct.startswith('stable')]
        if ctypes_stable:
            result['ctypes_stable'] = ctypes_stable
        else:
            match_success = False
            if ctypes_s:
                match_error = 'no stable ctypes found for %s, '\
                              'for non-stable ones add &ctype= to request' % service
            else:
                match_error = 'service %s not found anywhere' % service
    result.update({'match_success': match_success, 'match_error': match_error})
    return result


def get_all_slas():
    ctypes_res = cluster.get_ctypes()
    if not ctypes_res['success']:
        return ctypes_res
    ctypes = [ct for ct in ctypes_res['result']]
    slas = {}
    warnings = {}
    for ct in ctypes:
        slt = sla_table(ct, False, False)
        if slt['success']:
            slas[ct] = slt['result'].copy()
        else:
            warnings['on_sla_' + ct] = slt.get('error', 'unknown error')
    return {'success': len(slas) > 0, 'result': slas, 'warnings': warnings}
