package com.mortals.xhx.thread;


import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.AbstractThread;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 设备消息更新线程
 *
 * @author zxfei
 */
@Slf4j
@Service
@Order(value = 1)
public class DeviceUpdateComsumerThread extends AbstractThread {

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private DeviceService deviceService;

    @Override
    protected int getSleepTime() {
        return 1000;
    }

    @Override
    protected void process() {
        // log.info("DeviceUpdateComsumerThread process");
        List<DeviceEntity> waitUpdateDeviceList = new ArrayList<>();
        while (true) {
            DeviceEntity deviceEntity = cacheService.lpop(RedisKey.KEY_DEVICE_UPDATE_QUEUE, DeviceEntity.class);
            if (ObjectUtils.isEmpty(deviceEntity)) {
                //  log.info("deviceEntity:{}", deviceEntity == null);
                break;
            }
            waitUpdateDeviceList.add(deviceEntity);
        }
        if (!ObjectUtils.isEmpty(waitUpdateDeviceList)) {
            log.info("updateDeviceList size:{}", waitUpdateDeviceList.size());

            for (DeviceEntity deviceEntity : waitUpdateDeviceList) {
                deviceService.update(deviceEntity);
            }

        }

    }


    @Override
    protected void threadClosed() {
        // TODO Auto-generated method stub
        super.close();
    }


}
