from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from django.db import transaction
from .models import UserSettings
from .serializers import UserSettingsSerializer
from ErrorLogs.utils import log_error

# Create your views here.

class UserSettingsViewSet(viewsets.ModelViewSet):
    queryset = UserSettings.objects.all()
    serializer_class = UserSettingsSerializer

    def list(self, request, *args, **kwargs):
        try:
            return super().list(request, *args, **kwargs)
        except Exception as e:
            log_error('UserSettingsViewSet.list', e)
            return Response(
                {"error": "An error occurred while fetching user settings"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super().create(request, *args, **kwargs)
        except Exception as e:
            log_error('UserSettingsViewSet.create', e)
            return Response(
                {"error": "An error occurred while creating user settings"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def retrieve(self, request, *args, **kwargs):
        try:
            return super().retrieve(request, *args, **kwargs)
        except Exception as e:
            log_error('UserSettingsViewSet.retrieve', e)
            return Response(
                {"error": "An error occurred while fetching user settings details"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def update(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super().update(request, *args, **kwargs)
        except Exception as e:
            log_error('UserSettingsViewSet.update', e)
            return Response(
                {"error": "An error occurred while updating user settings"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super().destroy(request, *args, **kwargs)
        except Exception as e:
            log_error('UserSettingsViewSet.destroy', e)
            return Response(
                {"error": "An error occurred while deleting user settings"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
