# (c) cavaliba.com - registry.py

import json

from app_data.models import DataRegistry


def registry_get_key(key=None, unpack=None):
    if not key:
        return
    entry = DataRegistry.objects.filter(key=key).first()

    if not entry:
        return

    if not unpack:
        return entry.value

    if unpack == "json":
        try:
            return json.loads(entry.value)
        except Exception:
            pass

    return entry.value


# def registry_get_key_multi(key=None):

#     if not key:
#         return

#     reply = []
#     entries = DataRegistry.objects.filter(key=key)
#     for entry in entries:
#         reply.append(entry.value)
#     return reply


def registry_set_key(key=None, value=None, pack=None):

    if not key:
        return

    if pack == "json":
        try:
            value2 = json.dumps(value, indent=2, ensure_ascii=False)
        except Exception:
            value2 = value
    else:
        value2 = value

    entry = DataRegistry.objects.filter(key=key).first()
    if entry:
        entry.value = value2
        entry.save()
    else:
        entry = DataRegistry(key=key, value=value2)
        entry.save()


def registry_has_key(key=None):
    if not key:
        return False
    entry = DataRegistry.objects.filter(key=key).first()
    if entry:
        return True
    return False


def registry_delete_key(key=None):
    if not key:
        return False
    entry = DataRegistry.objects.filter(key=key).delete()
    return entry
