package com.aliyun.iotx;

import com.aliyun.iot.as.bridge.core.handler.tsl.TslUplinkHandler;
import com.aliyun.iot.as.bridge.core.model.Session;
import com.aliyun.iotx.bean.DataBean;
import com.aliyun.iotx.bean.DevSubBean;
import com.aliyun.iotx.bean.ExtBean;

import java.util.List;
import java.util.Random;

public class DataUtil {

    private final static Random random = new Random();

    public static void handleAndReport(DevSubBean devSubBean){
        ExtBean extBean = devSubBean.getExt();
        String originalIdentity = extBean.getStationID();

        String soilTemperature = "0";
        String soilHumidity = "0";
        String ph = "0";

        List<DataBean> dataBeanList = extBean.getData();
        for (DataBean dataBean : dataBeanList) {
            switch (dataBean.geteKey()) {
                case "e1":
                    soilTemperature = dataBean.geteValue();
                    break;
                case "e2":
                    soilHumidity = dataBean.geteValue();
                    break;
                case "e3":
                    ph = dataBean.geteValue();
                    break;
            }
        }

        onlineAndReportProperty(originalIdentity, soilTemperature, soilHumidity, ph);
    }

    // 上线+上报属性
    private static void onlineAndReportProperty(String originalIdentity, String soilTemperature, String soilHumidity, String ph){
        // device Session of your specific protocol, If none, you can just use empty object
        Object originalChannel = new Object();
        Session session = Session.newInstance(originalIdentity, originalChannel);
        // 设备上线
        TslUplinkHandler tslUplinkHandler = new TslUplinkHandler();
        tslUplinkHandler.doOnline(session, originalIdentity);
        // 上报属性
        String requestId = String.valueOf(random.nextInt(1000));
        tslUplinkHandler.reportProperty(requestId, originalIdentity, "soilTemperature", Double.parseDouble(soilTemperature));
        tslUplinkHandler.reportProperty(requestId, originalIdentity, "soilHumidity", Double.parseDouble(soilHumidity));
        tslUplinkHandler.reportProperty(requestId, originalIdentity, "soilPH", Double.parseDouble(ph));
    }
}
