import config from "../../config";
const core = require('@huaweicloud/huaweicloud-sdk-core');
const sis = require("@huaweicloud/huaweicloud-sdk-sis");



class HuaweiTTS {
  constructor(options) {
    //配置项
    this.ak = config.huawei.ak;
    this.sk = config.huawei.sk;
    this.endpoint = config.huawei.endpoint;
    this.project_id = config.huawei.projectId;
  }

  async textToVoice(text, params) {

    const credentials = new core.BasicCredentials()
      .withAk(params.token.tts.ak || this.ak)
      .withSk(params.token.tts.sk || this.sk)
      .withProjectId(params.token.tts.projectId || this.project_id)
    const client = sis.SisClient.newBuilder()
      .withCredential(credentials)
      .withEndpoint("https://" + params.token.tts.endpoint || this.endpoint)
      .build();
    const request = new sis.RunTtsRequest();
    const body = new sis.PostCustomTTSReq();
    const configbody = new sis.TtsConfig();
    delete params.token;
    for (var key in params) {
      switch (key) {
        case "property": { configbody.withProperty(params[key]); continue; }
        case "speed": { configbody.withSpeed(params[key]); continue; }
        case "volume": { configbody.withVolume(params[key]); continue; }
        case "pitch": { configbody.withPitch(params[key]); continue; }
        case "audio_format": { configbody.withAudioFormat(params[key]); continue; }
        case "sample_rate": { configbody.withSampleRate(params[key]); continue; }
      }
    }
    console.log("【Huawei TTS】 configbody>>>>>>>",configbody);
    body.withConfig(configbody);
    body.withText(text);
    request.withBody(body);
    console.log("【华为ASR】 request text:", text);

    var result = {};
    try {
      result = await client.runTts(request);
      result.status = 200;
    } catch (e) {
      result.statusText = e;
      result.status = 200;
    }
    return result;
  }
}

export default HuaweiTTS;