const { default: axios } = require("axios");
const CryptoJS = require("crypto-js");
const urlencode = require("urlencode");

class WarpDH {
  constructor(options) {
    this.appId = options.token.appId;
    this.appSecret = options.token.appSecret;
    this.host = options.token.host;
    this.config = options.config;
  }

  async init() {
    //处理param
    const path = "/private/v1/session/new";
    var apiUrl = this.host + path;
    var url = this.getUrl(this.appId, this.appSecret, apiUrl);
    var param = {
      protocol: this.config.params.protocol || "rtmp",
    };
    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);
      console.log("初始化接口返回:", result.data);
      result = await this.start(result.data.sessionId);
    } catch (e) {
      //   throw Error("初始化接口内部错误:" + e);
      console.log("初始化接口内部错误:", e);
    }
    return result;
  }

  async start(sessionId) {
    const path = "/private/v1/session/start";
    var apiUrl = this.host + path;
    var url = this.getUrl(this.appId, this.appSecret, apiUrl);
    var param = {
      sessionId: sessionId,
      modeluuid: "22234553-7175-4904-a2e0-f812c5a6db94",
      voiceuuid: "189e4313-6dd4-4e55-b84f-a24c66249571",
    };
    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);
      console.log("初始化接口内部错误:", e);
    }
    return result;
  }

  async command(param) {
    const path = "/private/v1/digital/humans";
    var apiUrl = this.host + path;
    var url = this.getUrl(this.accessKey, this.secretKey, apiUrl);
    param = {
      sessionId: param.sessionId,
      text: param.text,
    };
    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(appId, appSecret, apiUrl) {
    var ts = Math.round(new Date().getTime() / 1000).toString();
    //生成10位随机字符串
    var rnd = Math.random().toString(36).substring(2, 20);
    var signature = this.getSign(appId, ts, rnd, appSecret);
    console.log(signature);
    var url = `${apiUrl}?ak=${appId}&ts=${ts}&rnd=${rnd}&sign=${signature}`;
    console.log("url", url);
    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(ak, ts, rnd, as) {
    const content = `${ak}${ts}${rnd}`;
    return CryptoJS.HmacSHA256(content, as).toString(CryptoJS.enc.Hex);
  }
  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.WarpDH = WarpDH;
