from django.contrib.gis.measure import Distance
from service import models
from postamates.settings import DEFAULT_PLACEMENT_POINT_UPDATE_RADIUS


class LayerService:
    def count_post_pvz_for_placementpoint(self, obj):
        points = models.PlacementPoint.objects.filter(geometry__distance_lt=(obj.wkt, Distance(
            m=DEFAULT_PLACEMENT_POINT_UPDATE_RADIUS))).all()
        for point in points:
            LayerService.count_post_pvz(point)

    @staticmethod
    def update_categories(instance):
        groups = models.Post_and_pvzGroup.objects.filter(category=instance)
        groups.update(include_in_ml=instance.include_in_ml, visible=instance.visible)
        for gr in groups:
            models.RaschetGroups.objects.get_or_create(obj_id=gr.id)
            objects = models.Post_and_pvz.objects.filter(group=gr)
            objects.update(include_in_ml=instance.include_in_ml, visible=instance.visible)
            for obj in objects.all():
                models.RaschetObjects.objects.get_or_create(obj_id=obj.id)

    @staticmethod
    def update_groups(instance):
        models.RaschetGroups.objects.get_or_create(obj_id=instance.id)
        objects = models.Post_and_pvz.objects.filter(group=instance)
        objects.update(include_in_ml=instance.include_in_ml, visible=instance.visible)
        for obj in objects.all():
            models.RaschetObjects.objects.get_or_create(obj_id=obj.id)

    @staticmethod
    def get_post_and_pvz_categroies():
        return models.Post_and_pvzCategory.objects.all(), models.Post_and_pvzGroup.objects.all()

    @staticmethod
    def count_post_pvz(point):
        point.rival_post_cnt = models.Post_and_pvz.objects.filter(
            category__name="Постамат", include_in_ml=True,
            wkt__distance_lt=(point.geometry, Distance(m=DEFAULT_PLACEMENT_POINT_UPDATE_RADIUS))).count()
        point.rival_pvz_cnt = models.Post_and_pvz.objects.filter(
            category__name="ПВЗ", include_in_ml=True,
            wkt__distance_lt=(point.geometry, Distance(m=DEFAULT_PLACEMENT_POINT_UPDATE_RADIUS))).count()
        point.save()
