from typing import *
from pprint import pprint
import pytest
import logging
from django.contrib.auth.models import User, AnonymousUser
from wcd_settings.registries import (
    SettingsDTO, UserSettingsDescriptor, AppSettingsDescriptor, Registry,
)
from wcd_settings.resolvers import (
    AppSettingsResolver, UserSettingsResolver,
    make_app_resolver, make_user_resolver,
)
from wcd_settings.setters import make_app_setter, make_user_setter
from wcd_settings.models import AppSettings, UserSettings
from wcd_settings.views import AppSettingsAll, UserSettingsAll

from .fixtures import get_raw_response


@pytest.mark.django_db
def test_app_view_empty(rf, registry: Registry, simple_app_settings: AppSettingsDescriptor):
    request = rf.get('/')
    request.app_settings = make_app_setter(make_app_resolver(registry))

    response = get_raw_response(AppSettingsAll, request)

    assert len(response) == 1
    assert simple_app_settings.key in response
    assert response[simple_app_settings.key]['title'] is None


@pytest.mark.django_db
def test_user_view_empty(rf, registry: Registry, simple_app_settings: AppSettingsDescriptor):
    request = rf.get('/')
    request.user_settings = make_user_setter(make_user_resolver(registry))
    request.user = AnonymousUser()

    response = get_raw_response(UserSettingsAll, request)

    assert len(response) == 1
    assert simple_app_settings.key in response
    assert response[simple_app_settings.key]['title'] is None


@pytest.mark.django_db
def test_user_view(rf, registry: Registry, simple_user_settings: UserSettingsDescriptor):
    user = User.objects.create_user(username='test', password='test')
    UserSettings.objects.create(
        key=simple_user_settings.key, config={"title": "test"},
        user_id=user.pk,
    )

    request = rf.get('/')
    request.user_settings = make_user_setter(make_user_resolver(registry))
    request.user = AnonymousUser()

    response = get_raw_response(UserSettingsAll, request)

    assert len(response) == 1
    assert simple_user_settings.key in response
    assert response[simple_user_settings.key]['title'] is None

    request2 = rf.get('/')
    request2.user_settings = make_user_setter(make_user_resolver(registry))
    request2.user = user

    response = get_raw_response(UserSettingsAll, request2)

    assert len(response) == 1
    assert simple_user_settings.key in response
    assert response[simple_user_settings.key]['title'] == 'test'
