import time
from django.db import transaction
from console.equipment.models import Equipment, EquipmentData


class EquipmentService(object):
    @transaction.atomic()
    def delete_equipment(self, equipment_id):
        Equipment.objects.filter(id=equipment_id).update(
            deleted=True,
            deleted_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    @transaction.atomic()
    def delete_equipments(self, equipments):
        Equipment.objects.filter(id__in=equipments).update(
            deleted=True,
            deleted_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


    def create_equipments(self, equipment):
        data = equipment.pop("data", None)
        eq = Equipment.objects.create(**equipment)
        if data:
            eq_data = EquipmentData.objects.create(**data)
            eq.equipment_data_id = eq_data.id
            eq.save()


    @transaction.atomic()
    def operation_equipments(self, data):
        customer_id = data.get("customer_id")
        electricity_user_id = data.get("electricity_user_id")
        electrical_info_id = data.get("electrical_info_id")
        add = data.get("add")
        update = data.get("update")
        delete = data.get("delete", [])
        create_list = []
        for i in add:
            i.update({
                "customer_id": customer_id,
                "electricity_user_id": electricity_user_id,
                "electrical_info_id": electrical_info_id,
            })
            create_list.append(Equipment(**i))
        Equipment.objects.bulk_create(create_list)
        for j in update:
            j.update({
                "customer_id": customer_id,
                "electricity_user_id": electricity_user_id,
                "electrical_info_id": electrical_info_id,
            })
            Equipment.objects.filter(id=j["id"]).update(**j)
        if delete:
            Equipment.objects.filter(id__in=delete).delete()


equipment_service = EquipmentService()
