# Path: assessment/serializers.py
# class SurveySerializer(TranslatableModelSerializer):
#     _uid = serializers.UUIDField(label='ID', read_only=True)
#     translations = TranslatedFieldsField(shared_model=Survey)
#     questions = QuestionSerializer(many=True, read_only=True)
#     is_admin = serializers.SerializerMethodField()
#     in_users = serializers.SerializerMethodField()
#     result = serializers.SerializerMethodField(read_only=True)
#     name = serializers.SerializerMethodField(read_only=True)
#     description = serializers.SerializerMethodField(read_only=True)
# 
#     class Meta:
#         model = Survey
#         fields = (
#             '_uid',
#             'is_active',
#             'is_private',
#             'start_date_time',
#             'end_date_time',
#             'translations',
#             'questions',
#             'is_admin',
#             'in_users',
#             'result',
#             'name',
#             'description',
#         )
# 
#     def get_result(self, obj):
#         """
#         When an authenticated user request survey details,
#         it should include if the survey has been started, completed, etc.
#         """
#         try:
#             user = self.context.get('request').user
#         except Exception:
#             return {
#                 "status": "error",
#                 "result_id": None
#             }
# 
#         if user.id is None:
#             return {
#                 "status": "anonymous",
#                 "result_id": None
#             }
# 
#         try:
#             result = Result.objects.get(survey=obj, user=user)
#         except Result.DoesNotExist:
#             return {
#                 "status": "unstarted",
#                 "result_id": None
#             }
# 
#         if result.answers.count() == obj.questions.count():
#             return {
#                 "status": "complete",
#                 "result_id": str(result.pk)
#             }
#         else:
#             return {
#                 "status": "incomplete",
#                 "result_id": str(result.pk)
#             }
# 
#     def get_is_admin(self, obj):
#         """
#         The application should never directly report who the admin is.
#         This method reports if the current authenticated user is the admin.
#         """
#         try:
#             user = self.context.get('request').user
#         except Exception:
#             # raise serializers.ValidationError('Could not access request.user')
#             return False
#         if user == obj.admin:
#             return True
#         else:
#             return False
# 
#     def get_in_users(self, obj):
#         """
#         The application should never directly report the entire user group.
#         This method reports if the current authenticated user is users.
#         """
#         try:
#             user = self.context.get('request').user
#         except Exception:
#             # raise serializers.ValidationError('Could not access request.user')
#             return False
#         if user in obj.users.all():
#             return True
#         else:
#             return False
# 
#     def get_name(self, obj):
#         try:
#             return obj.name
#         except ObjectDoesNotExist:
#             return str(obj.pk)
# 
#     def get_description(self, obj):
#         try:
#             return obj.description
#         except ObjectDoesNotExist:
#             return str(obj.pk)
# 
# Path: assessment/models.py
# class Survey(TranslatableModel):
#     _uid = models.UUIDField(
#         primary_key=True,
#         editable=False,
#         default=uuid.uuid4,
#     )
# 
#     translations = TranslatedFields(
#         name=models.CharField(_("name"), max_length=160),
#         description=models.TextField(_("description")),
#     )
# 
#     is_active = models.BooleanField(
#         _("active"),
#         default=True,
#     )
# 
#     is_private = models.BooleanField(
#         _("private"),
#         default=False,
#     )
# 
#     start_date_time = models.DateTimeField(
#         _("start time"),
#         auto_now=False,
#         default=datetime.datetime.now,
#     )
# 
#     end_date_time = models.DateTimeField(
#         _("end time"),
#         auto_now=False,
#         null=True,
#         blank=True,
#     )
# 
#     admin = models.ForeignKey(
#         settings.AUTH_USER_MODEL,
#         on_delete=models.SET_NULL,
#         null=True,
#         related_name="assessment_admin_surveys",
#         verbose_name=_('owner'),
#     )
# 
#     users = models.ManyToManyField(
#         settings.AUTH_USER_MODEL,
#         related_name="assessment_user_surveys",
#         blank=True,
#     )
# 
#     class Meta:
#         app_label = 'assessment'
#         verbose_name = _("survey")
#         verbose_name_plural = _("surveys")
# 
#     def __str__(self):
#         return self.name


import logging
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from assessment.serializers import SurveySerializer
from assessment.models import Survey
        try:
            survey = Survey.objects.get(pk=uuid)
        except Survey.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        if request.user == survey.admin:
            serializer = SurveySerializer(survey, data=request.data, context={'request': request})
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({"error": "un-authorized"}, status=status.HTTP_403_FORBIDDEN)
    else:
        return Response({"error": "user not found"}, status=status.HTTP_404_NOT_FOUND)


@api_view(['GET', ])
def retrieve_survey(request, uuid):
    """
    return a single survey.
    """
    try:
        survey = Survey.objects.get(pk=uuid)
    except (Survey.DoesNotExist, ValueError):
        return Response({"error": "Survey not found"}, status=status.HTTP_404_NOT_FOUND)

    if survey.is_private:
        if request.user.is_authenticated:
            if request.user == survey.admin or request.user in survey.users.all():

# Path: assessment/serializers.py
# class SurveySerializer(TranslatableModelSerializer):
#     _uid = serializers.UUIDField(label='ID', read_only=True)
#     translations = TranslatedFieldsField(shared_model=Survey)
#     questions = QuestionSerializer(many=True, read_only=True)
#     is_admin = serializers.SerializerMethodField()
#     in_users = serializers.SerializerMethodField()
#     result = serializers.SerializerMethodField(read_only=True)
#     name = serializers.SerializerMethodField(read_only=True)
#     description = serializers.SerializerMethodField(read_only=True)
# 
#     class Meta:
#         model = Survey
#         fields = (
#             '_uid',
#             'is_active',
#             'is_private',
#             'start_date_time',
#             'end_date_time',
#             'translations',
#             'questions',
#             'is_admin',
#             'in_users',
#             'result',
#             'name',
#             'description',
#         )
# 
#     def get_result(self, obj):
#         """
#         When an authenticated user request survey details,
#         it should include if the survey has been started, completed, etc.
#         """
#         try:
#             user = self.context.get('request').user
#         except Exception:
#             return {
#                 "status": "error",
#                 "result_id": None
#             }
# 
#         if user.id is None:
#             return {
#                 "status": "anonymous",
#                 "result_id": None
#             }
# 
#         try:
#             result = Result.objects.get(survey=obj, user=user)
#         except Result.DoesNotExist:
#             return {
#                 "status": "unstarted",
#                 "result_id": None
#             }
# 
#         if result.answers.count() == obj.questions.count():
#             return {
#                 "status": "complete",
#                 "result_id": str(result.pk)
#             }
#         else:
#             return {
#                 "status": "incomplete",
#                 "result_id": str(result.pk)
#             }
# 
#     def get_is_admin(self, obj):
#         """
#         The application should never directly report who the admin is.
#         This method reports if the current authenticated user is the admin.
#         """
#         try:
#             user = self.context.get('request').user
#         except Exception:
#             # raise serializers.ValidationError('Could not access request.user')
#             return False
#         if user == obj.admin:
#             return True
#         else:
#             return False
# 
#     def get_in_users(self, obj):
#         """
#         The application should never directly report the entire user group.
#         This method reports if the current authenticated user is users.
#         """
#         try:
#             user = self.context.get('request').user
#         except Exception:
#             # raise serializers.ValidationError('Could not access request.user')
#             return False
#         if user in obj.users.all():
#             return True
#         else:
#             return False
# 
#     def get_name(self, obj):
#         try:
#             return obj.name
#         except ObjectDoesNotExist:
#             return str(obj.pk)
# 
#     def get_description(self, obj):
#         try:
#             return obj.description
#         except ObjectDoesNotExist:
#             return str(obj.pk)
# 
# Path: assessment/models.py
# class Survey(TranslatableModel):
#     _uid = models.UUIDField(
#         primary_key=True,
#         editable=False,
#         default=uuid.uuid4,
#     )
# 
#     translations = TranslatedFields(
#         name=models.CharField(_("name"), max_length=160),
#         description=models.TextField(_("description")),
#     )
# 
#     is_active = models.BooleanField(
#         _("active"),
#         default=True,
#     )
# 
#     is_private = models.BooleanField(
#         _("private"),
#         default=False,
#     )
# 
#     start_date_time = models.DateTimeField(
#         _("start time"),
#         auto_now=False,
#         default=datetime.datetime.now,
#     )
# 
#     end_date_time = models.DateTimeField(
#         _("end time"),
#         auto_now=False,
#         null=True,
#         blank=True,
#     )
# 
#     admin = models.ForeignKey(
#         settings.AUTH_USER_MODEL,
#         on_delete=models.SET_NULL,
#         null=True,
#         related_name="assessment_admin_surveys",
#         verbose_name=_('owner'),
#     )
# 
#     users = models.ManyToManyField(
#         settings.AUTH_USER_MODEL,
#         related_name="assessment_user_surveys",
#         blank=True,
#     )
# 
#     class Meta:
#         app_label = 'assessment'
#         verbose_name = _("survey")
#         verbose_name_plural = _("surveys")
# 
#     def __str__(self):
#         return self.name


# Path: assessment/views/api/survey.py
import logging
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from assessment.serializers import SurveySerializer
from assessment.models import Survey

        try:
            survey = Survey.objects.get(pk=uuid)
        except Survey.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        if request.user == survey.admin:
            serializer = SurveySerializer(survey, data=request.data, context={'request': request})
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({"error": "un-authorized"}, status=status.HTTP_403_FORBIDDEN)
    else:
        return Response({"error": "user not found"}, status=status.HTTP_404_NOT_FOUND)


@api_view(['GET', ])
def retrieve_survey(request, uuid):
    """
    return a single survey.
    """
    try:
        survey = Survey.objects.get(pk=uuid)
    except (Survey.DoesNotExist, ValueError):
        return Response({"error": "Survey not found"}, status=status.HTTP_404_NOT_FOUND)

    if survey.is_private:
        if request.user.is_authenticated:
            if request.user == survey.admin or request.user in survey.users.all():

                serializer = SurveySerializer(survey, context={'request': request})