const { default: axios } = require("axios");
const cryptoJs = require("crypto-js");
const  urlencode =require("urlencode");
const Logger = require('../../../../../utils/logger').Logger;
let logger = new Logger(__filename);


class TencenNewtDH {
    constructor(options) {
        this.host = options.token.host;
        this.wss = options.token.wss;
        this.accessKey = options.token.accessKey;
        this.secretKey = options.token.secretKey;
        this.config = options.config;
    };

    async init() {
        //处理param
        const path = "/v2/ivh/streammanager/streamservice/newsession";
        var apiUrl = this.host + path;
        var url = this.getUrl(this.accessKey, this.secretKey, apiUrl);
        var param = {
            "Header": {},
            "Payload": {
                "UserId": "00000001",
                "DriverType": 1,
                "Protocol": this.config.params.protocol||"flv"
            }
        }
        var options = {
            url: url,
            method: 'POST',
            headers: { "Content-Type": "application/json;charset=utf-8" },
            data: JSON.stringify(param)
        };
        var result = {};
        try {
            result = await axios(options)
            result = result.data;
        } catch (e) {
            throw Error("初始化接口内部错误:" + e);
        }
        return result;
    }

    async command(param) {
        const path = "/v2/ivh/streammanager/streamservice/command";
        var apiUrl = this.host + path;
        var url = this.getUrl(this.accessKey, this.secretKey, apiUrl);
         param = {
            "Header": {},
            "Payload": {
                "SessionId": param.topic,
                "Command": "SEND_TEXT",
                "Data": {
                    "Text": param.text,
                    "Interrupt": true
                }
            }
        }
        var options = {
            url: url,
            method: 'POST',
            headers: { "Content-Type": "application/json;charset=utf-8" },
            data: JSON.stringify(param)
        };
        var result = {};
        try {
            console.log("tencent dh requet:", options);
            result = await axios(options)
            console.log("tencent dh result:", result.data);
            result = result.data;
        } catch (e) {
            logger.error("初始化接口内部错误:", e);
            result.statusText = e;
            result.status = 500;
        }
        return result;
    }

    async commandChannel(param) {
        const path = "/v2/ws/ivh/streammanager/streamservice/commandchannel";
        var apiUrl = this.wss + path;
        var url = this.getWssUrl(this.accessKey, this.secretKey, apiUrl, param.topic);
        var result = url;
        console.log("tencent dh result:", result);
        return result;
    }

    getUrl(accessKey, secretKey, apiUrl) {
        var timestamp =Math.round(new Date().getTime() / 1000).toString()
        var content = "appkey=" + accessKey + "&timestamp=" + timestamp;
        var signature=this.getSign(content,secretKey);
        var url = apiUrl + "?" + content + "&signature=" + signature
        return url;
    }
    getWssUrl(accessKey, secretKey, apiUrl, topic) {
        var timestamp =Math.round(new Date().getTime() / 1000).toString()
        var content = "appkey=" + accessKey + "&requestid=" + topic + "&timestamp=" +timestamp;
        var signature=this.getSign(content,secretKey);
        var url = apiUrl + "?" + content + "&signature=" + signature
        console.log("url", url);
        return url;
    }

    getSign(content, accesstoken) {
        // const signBody = {
        //     appkey:appkey,
        //     timestamp: ts,
        // };
        // const sortedKeys = lodash.keys(signBody).sort();
        // let content = '';
        // for (const key of sortedKeys) {
        //     content += key + '=' + (typeof signBody[key] !== 'string' ? JSON.stringify(signBody[key]) : signBody[key]) + '&';
        // }
        // content = content.substring(0, content.length - 1);
        let sign = cryptoJs.enc.Base64.stringify(cryptoJs.HmacSHA256(content, accesstoken));
        sign = urlencode(sign);
        return sign;
    }
    getHeader(path, method) {
        const tim = Math.round(new Date().getTime() / 1000).toString()
        const pre = "sac-auth-v1/" + this.accessKey + "/" + tim + "/3600";
        var calc = pre + "\n" + method + "\n" + this.host + "\n" + path + "\n";
        const h_result = cryptoJs.HmacSHA256(calc, this.secretKey)
        const res = cryptoJs.enc.Base64.stringify(h_result)
        return {
            "Content-Type": 'multipart/form-data',
            "Authorization": pre + "/" + res
        }
    }
}



exports.TencenNewtDH = TencenNewtDH;