package com.jpsoft.shinestar.modules.common.utils;

import cn.hutool.crypto.digest.MD5;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamsOnlineListRequest;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamsOnlineListResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AliyunLiveUtil {
    public static String generateSignedUrl(String uri,String fileName,long expiredTime,String privateKey){
        String rand = "0";
        String uid = "0";

        String md5hash = MD5.create().digestHex(fileName + "-" + expiredTime + "-" + rand + "-" + uid + "-" + privateKey);

        String signedUrl = uri + fileName + "?auth_key=" + expiredTime + "-" + rand + "-" + uid + "-" + md5hash;

        return signedUrl;
    }

    public static List<DescribeLiveStreamsOnlineListResponse.LiveStreamOnlineInfo> queryPushStreamOnlineList(String regionId,
                                                                                                             String accessKeyId,String secret,
                                                                                                             String domainName,String appName,
                                                                                                             String streamName){
        List<DescribeLiveStreamsOnlineListResponse.LiveStreamOnlineInfo> list = null;

        IClientProfile profile = DefaultProfile.getProfile(
                regionId,            // 地域ID
                accessKeyId,        // 您的AccessKey ID
                secret);  // 您的AccessKey Secret

        IAcsClient client = new DefaultAcsClient(profile);

        DescribeLiveStreamsOnlineListRequest request = new DescribeLiveStreamsOnlineListRequest();

        // 您的加速域名。
        request.setDomainName(domainName);

        // 应用名称。AppName 不支持通配符（*）查询，且不支持模糊查询。
        request.setAppName(appName);

        // 流名称。StreamName不支持通配符（*）查询，但支持模糊查询 。
        request.setStreamName(streamName);

        // 流类型。取值范围：all, raw, trans
        request.setStreamType("all");

        // 指定是否模糊匹配流名称。取值：fuzzy：模糊匹配；strict：精准匹配。
        request.setQueryType("fuzzy");

        try {
            DescribeLiveStreamsOnlineListResponse response = client.getAcsResponse(request);
            list = response.getOnlineInfo();
        } catch (ClientException ex) {
            log.error(ex.getMessage(), ex);
        }

        if (list==null){
            //如果为空访问一个空队列
            list = new ArrayList<>();
        }

        return list;
    }
}
