package net.northking.cctp.device.util;

import net.northking.cctp.device.constants.DeviceConstants;
import net.northking.cctp.device.db.entity.CdDeviceStatus;
import net.northking.cctp.device.db.service.CdDeviceStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Component
public class DeviceStatusUtil {

    @Autowired
    private CdDeviceStatusService cdDeviceStatusService;

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    private final static Logger logger = LoggerFactory.getLogger(DeviceStatusUtil.class);

    public void updateMobStatus(CdDeviceStatus status){
        Lock lock = redisLockRegistry.obtain(DeviceConstants.MOB_DEVICE_LOCK + status.getId());
        try {
            if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {
                cdDeviceStatusService.updateByPrimaryKey(status);//1
            }
        }catch (Exception e){
            logger.error("更新移动设备状态异常:",e);
        }finally {
            lock.unlock();
        }
    }

    public void updatePcStatus(CdDeviceStatus status){
        Lock lock = redisLockRegistry.obtain(DeviceConstants.PC_DEIVCE_LOCK + status.getId());
        try {
            if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {
                cdDeviceStatusService.updateByPrimaryKey(status);//1
            }
        }catch (Exception e){
            logger.error("更新PC设备状态异常:",e);
        }finally {
            lock.unlock();
        }
    }
}
