import json
import redis

from django.http import HttpResponse

SOCKDIR = '/var/run/yandex/intrasearch/redis/'


def get_mem_usage():
    result = {}
    for instance in ('celery', 'general'):
        with redis.Redis.from_url(f'unix://{SOCKDIR}{instance}.sock') as client:

            maxmemory = float(client.config_get('maxmemory').get('maxmemory'))
            used_memory_rss = client.info(section='memory').get('used_memory_rss')

            usage = int(round(100 * used_memory_rss / maxmemory, 0))
            result[instance] = usage
    return result


def redis_mem_usage_check(request):
    status_code = 200
    warn = int(request.GET.get('warn') or 65)
    crit = int(request.GET.get('crit') or 85)

    try:
        mem_usage = get_mem_usage()
    except Exception as e:
        return HttpResponse(json.dumps({'error': str(e)}),
                            content_type='application/json', status=421)

    for usage in mem_usage.values():
        if usage > crit:
            status_code = 422
            break
        elif usage > warn:
            status_code = 421

    return HttpResponse(json.dumps(mem_usage), content_type='application/json', status=status_code)
