from typing import *

from django.http import HttpRequest

from wcd_settings.setters import SettingsSetter
from wcd_settings import shortcuts

from .base import BaseView, DescriptorResolverViewMixin


__all__ = (
    'DetailView',
    'AppSettingsAll', 'app_settings_all_view',
    'UserSettingsAll', 'user_settings_all_view',
)


class DetailView(DescriptorResolverViewMixin, BaseView):
    def get_descriptors(self, settings: SettingsSetter, request: HttpRequest):
        return [
            x for x in super().get_descriptors(settings, request)
            if x.is_readable
        ]

    def get_keys(self,settings: SettingsSetter, request: HttpRequest):
        return [x.key for x in self.get_descriptors(settings, request)]

    def settings(self, request: HttpRequest):
        return {}

    def get(self, request: HttpRequest):
        return self.render_to_response({
            'data': self.settings(request),
        })


class AppSettingsAll(DetailView):
    def settings(self, request: HttpRequest):
        settings = shortcuts.app_settings(request)
        keys = self.get_keys(settings, request)
        resolver = settings.resolver
        resolver.prepare(keys)

        return {
            key: dto.model_dump(mode='json')
            for key, dto in ((k, resolver.get(k)) for k in keys)
            if dto is not None
        }

app_settings_all_view = AppSettingsAll.as_view()


class UserSettingsAll(DetailView):
    guest_user_id: int = 0

    def settings(self, request: HttpRequest):
        user_id = request.user.pk if request.user.is_authenticated else self.guest_user_id
        settings = shortcuts.user_settings(request)
        keys = [(user_id, k) for k in self.get_keys(settings, request)]
        resolver = settings.resolver
        resolver.prepare(keys)

        return {
            key: dto.model_dump(mode='json')
            for (_, key), dto in ((k, resolver.get(k)) for k in keys)
            if dto is not None
        }

user_settings_all_view = UserSettingsAll.as_view()
