package com.ruoyi.iot.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.iot.constants.IotConstants;
import com.ruoyi.iot.domain.CurrentDatastream;
import com.ruoyi.iot.domain.CurrentDeviceData;
import com.ruoyi.iot.domain.IotDeviceInfo;
import com.ruoyi.iot.domain.IotDeviceSysInfo;
import com.ruoyi.iot.service.IotConverter;
import com.ruoyi.iot.util.IotUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wjh
 * 2024/9/29
 */
@Service
@Slf4j
public class IotConverterImpl implements IotConverter {
    @Override
    public IotDeviceInfo toIotDeviceInfo(CurrentDeviceData data) {
        if (data == null) {
            return null;
        }

        return this.toIotDeviceInfo(data.getDatastreams(), data.getTitle());
    }

    private IotDeviceInfo toIotDeviceInfo(List<CurrentDatastream> ds, String mac) {
        if (CollectionUtils.isEmptyElement(ds)) {
            return null;
        }

        IotDeviceInfo device = new IotDeviceInfo();
        device.setMac(mac);

        for (CurrentDatastream stream : ds) {
            LocalDateTime at = stream.getAt();
            device.setAt(at);

            String id = stream.getId(); // 数据点ID
            String value = stream.getValue().toString();    // 数据点取值，取最新的值
            switch (id) {
                case IotConstants.DS_SYS:
                    this.setSysInfo(device, value);
                    break;
                case IotConstants.DS_VER:
                    device.setVer(value);
                    break;
                default: break;
            }
        }
        return device;
    }

    private void setSysInfo(IotDeviceInfo device, String value) {
        if (device == null || StringUtils.isBlank(value)) {
            return;
        }

        IotDeviceSysInfo sys = IotUtil.toSysInfo(value);
        if (sys == null) {
            return;
        }
        device.setSys(sys);
    }

}
