package com.ruoyi.device.mqtt.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.device.config.MqttConfig;
import com.ruoyi.device.mqtt.api.constants.ApiPathConstants;
import com.ruoyi.device.mqtt.api.item.ClientInfo;
import com.ruoyi.device.mqtt.api.item.EmqxResult;
import jakarta.annotation.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * EMQX HTTP API 工具
 *
 * @author lwm
 */
@Component
public class EmqxApiUtil
{
    @Resource
    private MqttConfig mqttConfig;

    /**
     * 获取客户端信息
     *
     * @param deviceType 设备类型
     * @param deviceSn 设备 SN
     * @return 客户端信息
     */
    public EmqxResult<List<ClientInfo>> getClientInfo(String deviceType, Long deviceSn)
    {
        String url = mqttConfig.getApiPath()
            + String.format(ApiPathConstants.GET_CLIENT_INFO, getClientId(deviceType, deviceSn));
        return get(url, new TypeReference<>() {
        });
    }

    /**
     * 获取客户端ID
     *
     * @param deviceType 设备类型
     * @param deviceSn 设备 SN
     * @return 客户端ID
     */
    protected String getClientId(String deviceType, Long deviceSn)
    {
        String deviceSnFormat = String.format("%010d", deviceSn);
        return deviceType + ApiPathConstants.MIDDLELINE + deviceSnFormat;
    }

    /**
     * GET 请求
     *
     * @param url 请求地址
     * @param typeReference 返回数据类型
     * @return 返回数据
     */
    private <T> T get(String url, TypeReference<T> typeReference)
    {
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(mqttConfig.getApiUserName(), mqttConfig.getApiPassword());
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Void> entity = new HttpEntity<>(headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                url, HttpMethod.GET, entity, String.class);
        return JSON.parseObject(responseEntity.getBody(), typeReference);
    }
}
