from collections.abc import Iterable
from typing import Dict, Union, Any
from urllib.parse import urlencode

from django.conf import settings
from django.db.models import Model
from django.urls.base import reverse


def absolute_reverse(*args, **kwargs) -> str:
    return '{protocol}://{host}{url}'.format(
        protocol=settings.FEMIDA_PROTOCOL,
        host=settings.FEMIDA_HOST,
        url=reverse(*args, **kwargs),
    )


def dict_to_url_query_string(data: Dict[str, Union[Model, Any]]) -> str:
    """
    Преобразует словарь параметров в query-string
    """
    params = []
    for k, v in data.items():
        if isinstance(v, Model):
            params.append((k, v.id))
        elif isinstance(v, str):
            params.append((k, v.encode('utf-8')))
        elif isinstance(v, bool):
            # Явно приводим к строке в нижнем регистре, чтобы не падал фронт
            params.append((k, str(v).lower()))
        elif isinstance(v, Iterable):
            params.extend((k, i.id if isinstance(i, Model) else i) for i in v)
        elif v is None:
            params.append((k, ''))
        else:
            params.append((k, v))
    return urlencode(params)
