from django.db import models

class EsLocationUnavailableSeat(models.Model):
    location = models.ForeignKey("api.EsLocation", on_delete=models.SET_NULL,null=True)
    type = models.SmallIntegerField(db_comment="0 - Any, 1 - Wall, 2 - Window, 3 - Door, 4 - Pillar")
    cord_x = models.IntegerField()
    cord_y = models.IntegerField()
    created_by = models.BigIntegerField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_by = models.BigIntegerField(null=True)
    updated_at = models.DateTimeField(auto_now=True)

    TYPE_TO_CODE = {
        "any": 0,
        "wall": 1,
        "window": 2,
        "door": 3,
        "pillar": 4,
    }

    class Meta:
        db_table = "es_location_unavailable_seat"

    @staticmethod
    def bulk_insert(location_id, insert_list):
        edit_objs = []
        if insert_list:
            for item in insert_list:
                existing = EsLocationUnavailableSeat.objects.filter(location_id=location_id, cord_x=item["x"], cord_y=item["y"]).first()
                if existing:
                    if existing.type != item["type"]:
                        existing.type = item["type"]
                        existing.save()
                        edit_objs.append({
                            "type": item["type"],
                            "x": item["x"],
                            "y": item["y"],
                        })
                else:
                    new_obj = EsLocationUnavailableSeat.objects.create(
                        location_id=location_id,
                        type=item["type"],
                        cord_x=item["x"],
                        cord_y=item["y"])
                    edit_objs.append({
                        "type": new_obj.type,
                        "x": new_obj.cord_x,
                        "y": new_obj.cord_y,
                    })

        return edit_objs