package com.dji.sample.common.smsp;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class CallSmsp {
    public static String getSmspToken(String username,String password) {
        String pass = MD5.create().digestHex(password);
        String url = "https://smsp.jkec.info:4443/api/v1/login?_t=1722393429&username="+username+"&password="+pass;
        try {
            String response = sendGetRequest(url);
            log.debug("Response from API: " + response);
            JSONObject json = new JSONObject(response);
            JSONObject body = json.getJSONObject("EasyDarwin").getJSONObject("Body");
            return body.getStr("Token");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getRtmp(String token,String deviceSn) {
        String url = "https://smsp.jkec.info:4443/api/v1/channelstream/all?token="+token;
        try {
            String response = sendGetRequest(url);
            log.debug("Response from API: " + response);
            JSONObject json = new JSONObject(response);
            JSONArray dataArray = json.getJSONArray("data");
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject dataObject = dataArray.getJSONObject(i);
                if (deviceSn.equals(dataObject.getStr("ChannelName"))) {
                    return dataObject.getStr("RTMP");
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String sendGetRequest(String requestURL) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(requestURL);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return EntityUtils.toString(response.getEntity());
            } else {
                throw new RuntimeException("Failed : HTTP error code : " + statusCode);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    }


}
