import json
import logging

from intranet.trip.src.config import settings
from intranet.trip.src.lib.aeroclub.api import aeroclub
from intranet.trip.src.lib.aeroclub import enums


async def get_reference_list(query, reference_type, cache):
    cache_key = f'{reference_type.value.lower()}:{query}'

    if reference_type == enums.ReferenceType.city:
        suggest_from_cache = await cache.get(cache_key)
        if suggest_from_cache is not None:
            logging.info('Value for query "%s" got from cache', query)
            return json.loads(suggest_from_cache)

    result = await aeroclub.get_references(query, reference_type.value)

    if reference_type == enums.ReferenceType.city:
        logging.info('Value for query "%s" not found in cache, saving', query)
        await cache.set(
            cache_key,
            json.dumps(result),
            expire_after=settings.REDIS_CACHE_EXPIRE_AFTER
        )

    return result
