package com.dji.sample.common.smsp;

import cn.hutool.json.JSONObject;
import com.dji.sample.configuration.CustomConfiguration;
import com.dji.sample.manage.log.annotation.Log;
import com.dji.sample.manage.log.enums.BusinessType;
import com.dji.sample.manage.model.dto.ManageDeviceLivestreamUrlDTO;
import com.dji.sample.manage.model.dto.RtmpUrlDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpVersion;
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;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class CallSmsp {

    private static final String NODE_DATA = "data";
    private static final String NODE_EASYDARWIN = "EasyDarwin";
    private static final String NODE_BODY = "Body";
    private static final String NODE_TOKEN = "Token";
    private static final String NODE_DEVICE_NAME = "DeviceName";
    private static final String NODE_CHILDREN = "Children";
    private static final String NODE_RTMPPUSH = "RTMPPUSH";
    private static final String NODE_WEBRTC = "WEBRTC";
    private static final String NODE_CHANNELID = "ChannelID";
    private static final String HTTPS = "https";
    private static final String HTTP2 = "HTTP/1.2";






    public static Map<String,String> getSmspToken(String username,String password,String protocal) {
        String tokenUrl = HTTPS.equals(protocal) ? CustomConfiguration.smspTokenUrl2 : CustomConfiguration.smspTokenUrl;
        String url = tokenUrl+"?username="+username+"&password="+password;
        try {
            Map<String,String> response = sendGetRequest(url);
            log.info("Response from  getSmspToken API: " + response);
            if(response.get(NODE_DATA) != null) {
                JSONObject json = new JSONObject(response.get(NODE_DATA));
                JSONObject body = json.getJSONObject(NODE_EASYDARWIN).getJSONObject(NODE_BODY);
                response.put(NODE_TOKEN,body.getStr(NODE_TOKEN));
            }

            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static RtmpUrlDTO getRtmp(String token, String deviceSn, String protocal) {
        RtmpUrlDTO rtmpUrlDTO = new RtmpUrlDTO();
        List<ManageDeviceLivestreamUrlDTO> resultList = new ArrayList<>();
        String rUrl = HTTPS.equals(protocal) ? CustomConfiguration.smspRtmpUrl2 : CustomConfiguration.smspRtmpUrl;
        String url = rUrl+"?token="+token;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String,String> response = sendGetRequest(url);
            log.info("=="+protocal+"=="+rUrl+"========Response from getSmspRtmpUrl API : " + response);
            if(response.get(NODE_DATA) != null ){
                JsonNode rootNode = objectMapper.readTree(response.get(NODE_DATA));
                // 遍历顶层的设备列表
                for (JsonNode deviceNode : rootNode.get(NODE_DATA)) {
                    String deviceName = deviceNode.get(NODE_DEVICE_NAME).asText();
                    // 查找特定设备名
                    if (deviceSn.equals(deviceName)) {
                        // 获取该设备的子节点
                        JsonNode childrenNode = deviceNode.get(NODE_CHILDREN);
                        // 遍历子节点
                        for (JsonNode childNode : childrenNode) {
                            ManageDeviceLivestreamUrlDTO livestreamUrlDTO = new ManageDeviceLivestreamUrlDTO();
                            // 获取RTMP和WEBRTC数据
                            String rtmpUrl = childNode.get(NODE_RTMPPUSH).asText();
                            String webRtcUrl = childNode.get(NODE_WEBRTC).asText();
                            Integer channelID = childNode.get(NODE_CHANNELID).asInt();
                            livestreamUrlDTO.setChannelId(channelID);
                            livestreamUrlDTO.setRtmpUrl(rtmpUrl);
                            livestreamUrlDTO.setWebRtcUrl(webRtcUrl);

                            resultList.add(livestreamUrlDTO);
                        }
                    }
                }
            }
            rtmpUrlDTO.setList(resultList);
            if(response.get("message") != null) {
                rtmpUrlDTO.setMessage(response.get("message"));
            }
            return rtmpUrlDTO;
        } catch (Exception e) {
            e.printStackTrace();
            rtmpUrlDTO.setMessage("获取流媒体地址异常："+e.getMessage());
            return rtmpUrlDTO;
        }
    }

    private static Map<String,String> sendGetRequest(String requestURL) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(requestURL);
        if(requestURL.startsWith(HTTPS)) {
            httpGet.setProtocolVersion(new HttpVersion(1, 2));
        }
        CloseableHttpResponse response = httpClient.execute(httpGet);
        Map<String,String> resultMap = new HashMap<>();
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                resultMap.put("data",EntityUtils.toString(response.getEntity()));
                return resultMap;
            } else {
                log.debug("Failed : 流媒体平台错误 : " + statusCode +":"+response.getStatusLine().getReasonPhrase());
                resultMap.put("code",String.valueOf(statusCode));
                resultMap.put("message","Failed : 流媒体平台错误 : " + statusCode +":"+response.getStatusLine().getReasonPhrase());
                return resultMap;
            }
        } finally {
            response.close();
            httpClient.close();
        }
    }


}
