from django.conf import settings
from django.shortcuts import get_object_or_404

from territories_dashboard_lib.indicators_lib.models import Theme
from territories_dashboard_lib.website_lib.logic import (
    get_favorite_subtheme,
    get_favorite_theme,
)
from territories_dashboard_lib.website_lib.serializers import (
    serialize_indicator,
    serialize_sub_themes,
)


def get_favorite_indicators_ids(request):
    return (
        request.user.favorite_indicators.values_list("id", flat=True)
        if request.user.is_authenticated
        else []
    )


def get_themes(request):
    themes = list(Theme.objects.all().order_by("ordering"))
    if getattr(request.user, "has_favorite_indicators", None):
        favorite_theme = get_favorite_theme()
        themes = [favorite_theme] + themes
    return themes


def get_theme_and_sub_themes(request, theme_name):
    if theme_name == "favoris":
        theme = get_favorite_theme()
        indicators = (
            [
                serialize_indicator(indicator)
                for indicator in (
                    request.user.favorite_indicators.filter(
                        is_active=True, hidden=False
                    ).order_by("favorite_links__order")
                )
            ]
            if request.user.is_authenticated
            else []
        )
        sub_themes = [get_favorite_subtheme(indicators)]
    else:
        theme = get_object_or_404(Theme, name=theme_name)
        sub_themes = serialize_sub_themes(theme)
    return theme, sub_themes


def apply_filters(request, indicator):
    filters = []
    for dimension in indicator.dimensions.all():
        url_filters = request.GET.getlist(dimension.db_name)
        db_filters = [f for f in dimension.filters.all()]
        for f in db_filters:
            f.set_from_url = "!" + f.db_name in url_filters or f.db_name in url_filters
            f.current = (
                f.default
                and "!" + f.db_name not in url_filters
                or f.db_name in url_filters
            )
        filters.append([dimension, db_filters])
    return filters


def get_base_url(request):
    return (
        settings.BASE_URL
        if hasattr(settings, "BASE_URL")
        else request.build_absolute_uri("/")[:-1]
    )
