from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance

from froide.publicbody.models import PublicBody


from .amenity import AmenityProvider


class AmenityLocalProvider(AmenityProvider):
    '''
    Like Amenity provider but tries to find the public body
    for the amenity at its location
    '''
    NEARBY_RADIUS = 200

    def _get_publicbody(self, amenity):
        nearby_popular_pbs = PublicBody.objects.filter(
            geo__isnull=False
        ).filter(
            geo__dwithin=(amenity.geo, self.NEARBY_RADIUS)
        ).filter(
            geo__distance_lte=(amenity.geo, D(m=self.NEARBY_RADIUS))
        ).annotate(
            distance=Distance("geo", amenity.geo)
        ).order_by("-number_of_requests", "distance")[:1]

        if nearby_popular_pbs:
            return nearby_popular_pbs[0]

        return super()._get_publicbody(amenity)

@@ -406,16 +406,185 @@
 enity):%0A
+%0A        same_name_pbs = PublicBody.objects.filter(name=amenity.name)%0A        if same_name_pbs and same_name_pbs.count() == 1:%0A            return same_name_pbs.first()%0A%0A
         
@@ -590,24 +590,16 @@
  nearby_
-popular_
 pbs = Pu
@@ -944,12 +944,8 @@
 ce%22)
-%5B:1%5D
 %0A%0A  
@@ -965,60 +965,407 @@
 by_p
-opular_pbs:%0A            return nearby_popular_pbs%5B0%5D
+bs:%0A            by_name = nearby_pbs.filter(name=amenity.name)%0A            if by_name:%0A                return by_name.first()%0A            if self.kwargs.get('category'):%0A                by_cat = nearby_pbs.filter(%0A                    categories__name=self.kwargs%5B'category'%5D%0A                )%0A                if by_cat:%0A                    return by_cat.first()%0A            return nearby_pbs.first()
 %0A%0A  

Improve amenitiy/publicbody match (maybe)