from django.core.cache import cache

from saas_deploy.cluster import alerts_commands as dm_alerts

import json
import time


def sla_table_component(ctype, cache_reupdate=False, cache_only=False, component=''):
    CACHE_KEY = 'sla-table-' + ctype
    if component:
        CACHE_KEY += '-' + component
    result = cache.get(CACHE_KEY)

    success = True
    err = ''
    recached = False
    if result:
        if cache_reupdate:
            cache_rw = cache.get(CACHE_KEY + '-rewriter')
            if not cache_rw:
                result, err = dm_alerts.get_sla_table(ctype, component)
                success = not err
                if success:
                    cache.set(CACHE_KEY, result, 900)
                    cache.set(CACHE_KEY + '-rewriter', '1', 60)
                    recached = True
        return {'success': success, 'result': result, 'error': err, 'recached': recached}

    if not result:
        if cache_only:
            return {'success': False, 'error': 'not found in cache'}
        result, err = dm_alerts.get_sla_table(ctype, component)
        success = not err
        if success:
            cache.set(CACHE_KEY, result, 900)
            cache.set(CACHE_KEY + '-rewriter', '1', 60)
            recached = True
    return {'success': success, 'result': result, 'error': err, 'recached': recached}


def sla_table(ctype, cache_reupdate=False, cache_only=False):
    sla_services = sla_table_component(ctype, cache_reupdate, cache_only, '')
    sla_metaservices = sla_table_component(ctype, cache_reupdate, cache_only, 'metaservice')
    result = {'success': sla_services['success'] and sla_metaservices['success'],
              'error': (('services: ' + sla_services['error']) if sla_services.get('error') else '')
                       + ((', metaservices: ' + sla_metaservices['error']) if sla_metaservices.get('error') else ''),
              'recached': sla_services['recached'] or sla_metaservices['recached'],
              'result': {}
              }
    if sla_services['success']:
        result['result'] = json.loads(sla_services['result'])
    if sla_metaservices['success']:
        result['result'].update(json.loads(sla_metaservices['result']))

    return result


def update_all(ctypes):
    result = {'sla': {}}
    for ct in ctypes:
        ts = int(time.time())
        ctres_in = sla_table(ct, cache_reupdate=True)
        ctres = {'success': ctres_in['success'],
                 'recached': ctres_in.get('recached', False)}
        if ctres_in.get('error'):
            ctres['error'] = ctres_in['error']
        ctres['time_sec'] = int(time.time()) - ts
        result['sla'][ct] = ctres
    return result
