package com.muyu.carData.interfaces;

import com.muyu.carData.annotation.IoTTableName;
import com.muyu.carData.domain.IoTDBRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * @Author：张腾
 * @Package：com.muyu.carData.interfaces
 * @Project：cloud-server-8
 * @name：IoTDBRecordable
 * @Date：2024/9/27 19:22
 * iot基类
 */
public interface IoTDBRecordable {

    Logger logger = LoggerFactory.getLogger(IoTDBRecordable.class);

    /**
     * 数据载入方法
     * @return Record
     */
    default IoTDBRecord toRecord() throws Exception {
        IoTDBRecord ioTDBRecord = new IoTDBRecord();
        Object getIoTDBTime = this.getClass().getMethod("getIoTDBTime").invoke(this);
        if (null != getIoTDBTime){
            ioTDBRecord.setTime((Long) getIoTDBTime);
        }
        Class aClass = this.getClass();
        IoTTableName name = this.getClass().getAnnotation(IoTTableName.class);
        ioTDBRecord.setDeviceId(name.value());
        Field[] declaredFields = aClass.getDeclaredFields();
        ArrayList<String> measurements = new ArrayList<>();
        ArrayList<Object> records = new ArrayList<>();
        ArrayList<String> types = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            measurements.add(declaredField.getName());
            String methodNamePro = declaredField.getName().substring(0, 1).toUpperCase() + declaredField.getName().substring(1);
            Method methodName = this.getClass().getMethod("get" + methodNamePro);
            records.add(methodName.invoke(this));
            types.add(methodName.getReturnType().getName());
        }
        ioTDBRecord.setMeasurementList(measurements);
        ioTDBRecord.setValueList(records);
        ioTDBRecord.setTypeList(types);
        return ioTDBRecord;
    }
}
