# Path: services/serializers.py
# class ServiceSerializer(serializers.ModelSerializer):
#     """ Usage:
#         from rest_framework.renderers import JSONRenderer
#         from semillas_backend.users.serializers import UserSerializer
# 
#         JSONRenderer().render(UserSerializer(user_instance).data)
#     """
#     category = CategorySerializer()
#     photos = serializers.SerializerMethodField('get_photos_list')
#     author = UserSerializer()
#     lat = serializers.SerializerMethodField()
#     lon = serializers.SerializerMethodField()
#     distance = serializers.SerializerMethodField()
# 
#     class Meta:
#         model = Service
#         fields = ('uuid', 'title', 'date', 'description', 'author', 'category', 'photos', 'seeds_price', 'lat', 'lon', 'distance')
# 
#     def get_photos_list(self, instance):
#         photos = ServicePhoto.objects\
#             .filter(service__id=instance.id)\
#             .order_by('date')
#         if not photos:
#             photos = [ServicePhoto(
#                 date=datetime.now(),
#                 photo=settings.SERVICE_PLACEHOLDER_PHOTO
#                 )]
#         return ServicePhotoSerializer(photos, many=True).data
# 
#     def get_lat(self, obj):
#         return getattr(obj.author.location, 'y', 0)
# 
#     def get_lon(self, obj):
#         return getattr(obj.author.location, 'x', 0)
# 
#     def get_distance(self, obj):
#         if hasattr(obj, 'dist') and (obj.dist != None):
#             distance = obj.dist.km
#             return round(distance, 1)
#         elif (not hasattr(obj, 'dist')) \
#                 and 'request' in self.context \
#                 and hasattr(self.context['request'].user, 'location') \
#                 and hasattr(obj.author, 'location') \
#                 and (obj.author.location):
#             distance = obj.author.location.distance(self.context['request'].user.location) * 100
#             return round(distance,1)
#         return None
# 
# Path: services/factory.py
# class ServiceFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Service
# 
#     title = factory.LazyAttribute(lambda x: faker.sentence(nb_words=3))
#     description = factory.LazyAttribute(lambda x: faker.sentence(nb_words=20))
#     author = factory.Iterator(User.objects.all())
#     category = factory.Iterator(Category.objects.all())
#     date = factory.Sequence(lambda n: datetime.datetime.now() + datetime.timedelta(days=n))
#     seeds_price = factory.Faker('pyint')
#     photo1 = factory.RelatedFactory(ServicePhotoFactory, 'service')
#     photo2 = factory.RelatedFactory(ServicePhotoFactory, 'service')
#     photo3 = factory.RelatedFactory(ServicePhotoFactory, 'service')
# 
# class CategoryFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Category
# 
# Path: services/factory.py
# class ServicePhotoFactory(factory.django.DjangoModelFactory):
#     class Meta:
# class ServiceFactory(factory.django.DjangoModelFactory):
#     class Meta:
# class CategoryFactory(factory.django.DjangoModelFactory):
#     class Meta:
# 
# Path: semillas_backend/users/models.py
# class User(AbstractUser):
# 
#     uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
#     # First Name and Last Name do not cover name patterns
#     # around the globe.
#     name = models.CharField(_('Name of User'), blank=True, max_length=255)
# 
#     phone = PhoneNumberField(blank=True)
#     phone_verified = models.BooleanField(default=False)
# 
#     location = PointField(
#         null=True,
#         blank=True,
#         help_text='User Location, only read in production user admin panel'
#     )
# 
#     location_manually_set = models.BooleanField(
#         default=False,
#         help_text="Flag indicating whether the user has introduced their location or not"
#     )
# 
#     def user_photo_upload(instance, filename):
#         extension = os.path.splitext(filename)[1]
#         return "media/users/%s-%s%s" % (str(instance.id), str(randint(0, 9999)), extension)
# 
#     picture = models.ImageField(
#         null=True,
#         blank=True,
#         help_text='Profile Picture',
#         upload_to=user_photo_upload,
#     )
# 
#     faircoin_address = models.CharField(
#         max_length=36,
#         blank=True,
#         validators=[is_blockchain_address]
#     )
# 
#     telegram_id = models.CharField(
#         blank=True,
#         max_length=60,
#         validators=[starts_with_at],
#         help_text="Telegram Id for peer communication. Example: @username"
#     )
# 
#     def __str__(self):
#         return self.username
# 
#     def get_absolute_url(self):
#         return reverse('users:detail', kwargs={'username': self.username})


from test_plus.test import TestCase
from ..views import FeedServiceList
from ..views import ServiceDetail
from ..views import UserServiceList
from ..serializers import ServiceSerializer
from rest_framework.test import force_authenticate
from rest_framework.test import APIRequestFactory
from django.contrib.gis.geos import Point
from django.conf import settings
from django.urls import reverse
from semillas_backend.users.factory import UserFactory
from services.factory import ServiceFactory, CategoryFactory
from services.factory import categories
from services.models import Service, Category
from semillas_backend.users.models import User
        # Generate a request search for "testing" key word
        request = self.factory.get(
            '/api/v1/service/feed?lat=%s&lon=%s' % (
                location_rome.coords[1],
                location_rome.coords[0]))

        # Attach the user to the request
        force_authenticate(request, user=self.users[3])

        self.view = FeedServiceList.as_view()
        response = self.view(request)

        # Expect: expect queryset of services ordered by proximity
        #   self.make_user()
        self.assertEqual(
            response.status_code,
            200
        )

        self.assertIsInstance(
            response.data,
            list
        )

        self.assertEqual(
            [item["title"] for item in response.data],
            ['5', '2', '4', '1', '3']
        )

        # Check the user location is not updated

# Path: services/serializers.py
# class ServiceSerializer(serializers.ModelSerializer):
#     """ Usage:
#         from rest_framework.renderers import JSONRenderer
#         from semillas_backend.users.serializers import UserSerializer
# 
#         JSONRenderer().render(UserSerializer(user_instance).data)
#     """
#     category = CategorySerializer()
#     photos = serializers.SerializerMethodField('get_photos_list')
#     author = UserSerializer()
#     lat = serializers.SerializerMethodField()
#     lon = serializers.SerializerMethodField()
#     distance = serializers.SerializerMethodField()
# 
#     class Meta:
#         model = Service
#         fields = ('uuid', 'title', 'date', 'description', 'author', 'category', 'photos', 'seeds_price', 'lat', 'lon', 'distance')
# 
#     def get_photos_list(self, instance):
#         photos = ServicePhoto.objects\
#             .filter(service__id=instance.id)\
#             .order_by('date')
#         if not photos:
#             photos = [ServicePhoto(
#                 date=datetime.now(),
#                 photo=settings.SERVICE_PLACEHOLDER_PHOTO
#                 )]
#         return ServicePhotoSerializer(photos, many=True).data
# 
#     def get_lat(self, obj):
#         return getattr(obj.author.location, 'y', 0)
# 
#     def get_lon(self, obj):
#         return getattr(obj.author.location, 'x', 0)
# 
#     def get_distance(self, obj):
#         if hasattr(obj, 'dist') and (obj.dist != None):
#             distance = obj.dist.km
#             return round(distance, 1)
#         elif (not hasattr(obj, 'dist')) \
#                 and 'request' in self.context \
#                 and hasattr(self.context['request'].user, 'location') \
#                 and hasattr(obj.author, 'location') \
#                 and (obj.author.location):
#             distance = obj.author.location.distance(self.context['request'].user.location) * 100
#             return round(distance,1)
#         return None
# 
# Path: services/factory.py
# class ServiceFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Service
# 
#     title = factory.LazyAttribute(lambda x: faker.sentence(nb_words=3))
#     description = factory.LazyAttribute(lambda x: faker.sentence(nb_words=20))
#     author = factory.Iterator(User.objects.all())
#     category = factory.Iterator(Category.objects.all())
#     date = factory.Sequence(lambda n: datetime.datetime.now() + datetime.timedelta(days=n))
#     seeds_price = factory.Faker('pyint')
#     photo1 = factory.RelatedFactory(ServicePhotoFactory, 'service')
#     photo2 = factory.RelatedFactory(ServicePhotoFactory, 'service')
#     photo3 = factory.RelatedFactory(ServicePhotoFactory, 'service')
# 
# class CategoryFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Category
# 
# Path: services/factory.py
# class ServicePhotoFactory(factory.django.DjangoModelFactory):
#     class Meta:
# class ServiceFactory(factory.django.DjangoModelFactory):
#     class Meta:
# class CategoryFactory(factory.django.DjangoModelFactory):
#     class Meta:
# 
# Path: semillas_backend/users/models.py
# class User(AbstractUser):
# 
#     uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
#     # First Name and Last Name do not cover name patterns
#     # around the globe.
#     name = models.CharField(_('Name of User'), blank=True, max_length=255)
# 
#     phone = PhoneNumberField(blank=True)
#     phone_verified = models.BooleanField(default=False)
# 
#     location = PointField(
#         null=True,
#         blank=True,
#         help_text='User Location, only read in production user admin panel'
#     )
# 
#     location_manually_set = models.BooleanField(
#         default=False,
#         help_text="Flag indicating whether the user has introduced their location or not"
#     )
# 
#     def user_photo_upload(instance, filename):
#         extension = os.path.splitext(filename)[1]
#         return "media/users/%s-%s%s" % (str(instance.id), str(randint(0, 9999)), extension)
# 
#     picture = models.ImageField(
#         null=True,
#         blank=True,
#         help_text='Profile Picture',
#         upload_to=user_photo_upload,
#     )
# 
#     faircoin_address = models.CharField(
#         max_length=36,
#         blank=True,
#         validators=[is_blockchain_address]
#     )
# 
#     telegram_id = models.CharField(
#         blank=True,
#         max_length=60,
#         validators=[starts_with_at],
#         help_text="Telegram Id for peer communication. Example: @username"
#     )
# 
#     def __str__(self):
#         return self.username
# 
#     def get_absolute_url(self):
#         return reverse('users:detail', kwargs={'username': self.username})


# Path: services/tests/test_views.py
from test_plus.test import TestCase
from ..views import FeedServiceList
from ..views import ServiceDetail
from ..views import UserServiceList
from ..serializers import ServiceSerializer
from rest_framework.test import force_authenticate
from rest_framework.test import APIRequestFactory
from django.contrib.gis.geos import Point
from django.conf import settings
from django.urls import reverse
from semillas_backend.users.factory import UserFactory
from services.factory import ServiceFactory, CategoryFactory
from services.factory import categories
from services.models import Service, Category
from semillas_backend.users.models import User

        # Generate a request search for "testing" key word
        request = self.factory.get(
            '/api/v1/service/feed?lat=%s&lon=%s' % (
                location_rome.coords[1],
                location_rome.coords[0]))

        # Attach the user to the request
        force_authenticate(request, user=self.users[3])

        self.view = FeedServiceList.as_view()
        response = self.view(request)

        # Expect: expect queryset of services ordered by proximity
        #   self.make_user()
        self.assertEqual(
            response.status_code,
            200
        )

        self.assertIsInstance(
            response.data,
            list
        )

        self.assertEqual(
            [item["title"] for item in response.data],
            ['5', '2', '4', '1', '3']
        )

        # Check the user location is not updated

        self.users[3] = User.objects.get(id=self.users[3].id)