from django.db.models import Q

from events.accounts.models import User, UserSettings
from events.v3.errors import ValidationError, MissingError
from events.v3.schemas import UserSettingsSchemaIn, UserSettingsSchemaOut


def get_user_view(request):
    return request.user


def get_user_by_id_view(request, user_id: int):
    return User.objects.get(pk=user_id)


def get_user_by_uid_view(request, uid: str = None, cloud_uid: str = None):
    if not uid and not cloud_uid:
        raise ValidationError([
            MissingError(loc=['uid']),
            MissingError(loc=['cloud_uid']),
        ])
    conditions = Q()
    if uid:
        conditions |= Q(uid=uid)
    if cloud_uid:
        conditions |= Q(cloud_uid=cloud_uid)
    return User.objects.get(conditions)


def get_user_settings_view(request) -> UserSettingsSchemaOut:
    try:
        user_settings = UserSettings.objects.get(user=request.user)
    except UserSettings.DoesNotExist:
        _settings = {}
    else:
        _settings = user_settings.settings
    return UserSettingsSchemaOut(id=request.user.id, settings=_settings)


def post_user_settings_view(request, data: UserSettingsSchemaIn) -> UserSettingsSchemaOut:
    user_settings = UserSettings.objects.get_or_create(user=request.user)[0]
    user_settings.settings = data.settings
    user_settings.save()
    return UserSettingsSchemaOut(id=request.user.id, settings=user_settings.settings)


def delete_user_settings_view(request):
    UserSettings.objects.filter(user=request.user).delete()
