package com.ruoyi.cai.trd;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.yunxin.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class Agora {

    @Autowired
    private AgoraProperties agoraProperties;

    public String getAuthorizationHeader(){
        // 拼接客户 ID 和客户密钥并使用 base64 编码
        String plainCredentials = agoraProperties.getKey() + ":" + agoraProperties.getSecret();
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // 创建 authorization header
        return "Basic " + base64Credentials;
    }


    public List<String> getChannelUsers(Long roomId){
        String url = "http://api.sd-rtn.com/dev/v1/channel/user/%s/%s";
        url = String.format(url, agoraProperties.getAppId(), roomId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", getAuthorizationHeader());
        HttpEntity httpEntity = new HttpEntity<>(headers);
        JSONObject jsonobject = RestTemplateUtil.restTemplate.getForObject(url,JSONObject.class,httpEntity);
        // "success":true,"data":{"channel_exist":true,"mode":2,"broadcasters":[1001,1025],"audience":[],"audience_total":0}}
        if(jsonobject == null){
            return Collections.emptyList();
        }
        JSONArray jsonArray = jsonobject.getJSONObject("data").getJSONArray("broadcasters");
        return jsonArray.toJavaList(String.class);
    }

    public void closeChannel(Long roomId){
        String url = "http://api.sd-rtn.com/dev/v1/kicking-rule";
        Map<String,Object> bodyData = new HashMap<>();
        bodyData.put("appid",agoraProperties.getAppId());
        bodyData.put("cname",roomId);
        bodyData.put("time",0);
        bodyData.put("privileges",Collections.emptyList());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", getAuthorizationHeader());
        HttpEntity httpEntity = new HttpEntity<>(bodyData, headers);
        RestTemplateUtil.restTemplate.postForObject(url, httpEntity, JSONObject.class);
    }

}
