from typing import Set
from waffle.models import Switch
import waffle as waffle_internal

from django.conf import settings
from django.core.cache import caches


SWITCH_CACHE = caches['switches']


def preload_all() -> None:
    for name, is_active in Switch.objects.all().values_list('name', 'active'):
        SWITCH_CACHE.set(name, is_active, settings.SWITCH_CACHE_TIMEOUT_SECONDS)


def preload(switch_names: Set[str]) -> None:
    if all(switch in SWITCH_CACHE for switch in switch_names):
        return

    switch_states = dict(Switch.objects.filter(name__in=switch_names).values_list('name', 'active'))

    for name in switch_names:
        SWITCH_CACHE.set(name, switch_states.get(name, False), settings.SWITCH_CACHE_TIMEOUT_SECONDS)


def switch_is_active(switch_name: str) -> bool:
    is_active = SWITCH_CACHE.get(switch_name, None)

    if is_active is None:
        is_active = waffle_internal.switch_is_active(switch_name)
        SWITCH_CACHE.set(switch_name, is_active, settings.SWITCH_CACHE_TIMEOUT_SECONDS)

    return is_active
