package com.zsc.edu.gateway.service.iot;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.gateway.domain.iot.DeviceBuilder;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.iot.device.dto.DeviceDto;
import com.zsc.edu.gateway.modules.iot.device.entity.Device;
import com.zsc.edu.gateway.modules.iot.device.repo.DeviceRepository;
import com.zsc.edu.gateway.modules.iot.device.service.DeviceService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
public class DeviceServiceTest {
    @Autowired
    private DeviceService service;
    @Autowired
    private DeviceRepository repo;

    private Device device1;
    private Device device2;

    @BeforeEach
    void setUp() {
        device1 = DeviceBuilder.aDevice().name("DEVICE_NAME_1").online(true).state(Device.Status.ACTIVATED).build();
        repo.insert(device1);
        device2 = DeviceBuilder.aDevice().name("DEVICE_NAME_2").online(false).state(Device.Status.ACTIVATED).build();
        repo.insert(device2);
    }

    @AfterEach
    void tearDown() {
        repo.delete(new LambdaQueryWrapper<Device>()
                .in(Device::getName, "DEVICE_NAME_1", "DEVICE_NAME_2", "DEVICE_3", "DEVICE_UPDATE"));
    }

    @Test
    void list() {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        assertEquals(2, service.list(queryWrapper.like(Device::getName, "DEVICE")).size());
        assertEquals(1, service.list(queryWrapper.eq(Device::getName, device1.getName())).size());
//        assertEquals(2, service.list().size());
    }

    @Test
    void createProduct() {
        DeviceDto dto = new DeviceDto("DEVICE_3", null, null, null, null, 121L, "备注");
        Device device = service.create(dto);
        assertNotNull(device);
        List<Device> devices = service.list(new LambdaQueryWrapper<Device>().like(Device::getName, "DEVICE"));
        assertEquals(3, devices.size());
        // 不能创建其他已存在的同名同代码部门
        DeviceDto dto2 = new DeviceDto(device2.getName(), null, null, null, null, 121L, "备注");
        assertThrows(ConstraintException.class, () -> service.create(dto2));
    }

    @Test
    void updateProduct() {
        DeviceDto dto = new DeviceDto();
        dto.setName("DEVICE_UPDATE");
        service.update(dto, device2.getId());
        Device updatedProduct = repo.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getName, dto.getName()));
        assertNotNull(updatedProduct);
        assertEquals("DEVICE_UPDATE", updatedProduct.getName());
        assertEquals(device2.getId(), updatedProduct.getId());
    }
}
