
var appKey = "154838659000009e";
var secretKey = "e35b157960dca3e56407f7d1acda7f17";
var userId = "iplayabc";
var baseUrl = "http://api.stkouyu.com:8080/";

function getConSig(){
	var timestamp = new Date().getTime().toString();
	var sig = new jsSHA(appKey + timestamp + secretKey, 'TEXT').getHash("SHA-1", "HEX");
	return {sig:sig, timestamp: timestamp};
}
function getStartSig(){
	var timestamp = new Date().getTime().toString();
	var sig = new jsSHA(appKey + timestamp + userId + secretKey, 'TEXT').getHash("SHA-1", "HEX");
	return {sig:sig, timestamp: timestamp, userId: userId};
}
var createUUID = (function (uuidRegEx, uuidReplacer) {
	return function () {
		return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
	};
})(/[xy]/g, function (c) {
	var r = Math.random() * 16 | 0,
			v = c == "x" ? r : (r & 3 | 8);
	return v.toString(16);
});


var pubskyparms = null;
function initSkKouYuParms(refText="", coreType="para.eval") {
    var audioType = "mp3"; //音频格式，支持wav,mp3,ogg,opus等多种格式
    var sampleRate = 16000; //音频采样率
    var conSig = getConSig();
    var startSig = getStartSig();
    pubskyparms = {
      connect:{
        cmd: "connect",
        param: {
          sdk: {
            version: 16777472,
            source: 9,
            protocol: 2
          },
          app: {
            applicationId: appKey,
            sig: conSig.sig,
            timestamp: conSig.timestamp
          }
        }
      },
      start: {
        cmd: "start",
        param: {
          app: {
            applicationId: appKey,
            sig: startSig.sig,
            userId: startSig.userId,
            timestamp: startSig.timestamp
          },
          audio: {
            audioType: audioType,
            sampleRate: sampleRate,
            channel: 1,
            sampleBytes: 2
          },
          request: {
            getParam: 1,
            attachAudioUrl: 1,
            coreType: coreType,
            refText: refText,
            tokenId: createUUID()
          }
        }
      }
    };
}

var priOss = null;
async function getOssInstanse() {
  if (priOss) {
    return priOss; 
  }
  const stmp = Date.now();
  const salt = 'iplayABC2019';
  const sign = hex_md5(stmp + salt);
  const res = await global.middleLayer.asyncCallNetworkApiGet(`/oss/sts`, {stmp, sign});
  const ossConfig = JSON.parse(res).data;
  priOss = new OSS({
    accessKeyId: ossConfig.AccessKeyId,
    accessKeySecret: ossConfig.AccessKeySecret,
    stsToken: ossConfig.SecurityToken,
    refreshSTSToken: ossConfig.SecurityToken,
    refreshSTRokeInterval: 3000000,
    bucket: ossConfig.bucket,
    region: ossConfig.region
  });
  return priOss; 
}

var priRecorder = null;

function getWebRecordInstanse() {
  return priRecorder;
}

export function initRecorder() {
  if (cc.sys.isBrowser && !priRecorder) {
    priRecorder = new Recorder({
      sampleRate: 44100, // 采样频率，默认为44100Hz(标准MP3采样率)
      bitRate: 128, // 比特率，默认为128kbps(标准MP3质量)
      success() {
        // 成功回调函数
        console.log(`初始化录音组件成功`);
      },
      error() {
        // 失败回调函数
        console.error(`初始化录音组件出错`);
      }, 
      fix() {
        // 不支持H5录音回调函数
        console.error(`该浏览器环境不支持录音，推荐使用谷歌浏览器`);
      } 
    });
  }
}

var isSpeechToText;
export function supportMethod (method, param) {
  if (cc.sys.isNative) {
    // 原生调用
    const paramStr = JSON.stringify(param);
    if (cc.sys.os == cc.sys.OS_IOS) {
      return jsb.reflection.callStaticMethod('RootViewController', `${method}:`, paramStr);
    }
    if (cc.sys.os == cc.sys.OS_ANDROID) {
      return jsb.reflection.callStaticMethod('com/iplayabc/cocos/AppActivity', method, '(Ljava/lang/String;)Ljava/lang/String;', paramStr);
    }
    if (cc.sys.os == cc.sys.OS_WINDOWS) {
      console.error('暂不支持此平台');
    }
  } else if (cc.sys.isBrowser) {
    if(method == 'getEngineInfo'){
      window.air.getEngineInfoCallback({isDev: 1, uuid: 'debug-njstar-xxxxxx'});
    } else if (method == 'startTest') {
      // 初始化参数
      initSkKouYuParms(param.params, 'para.eval');
      const rec = getWebRecordInstanse();
      rec.start();
    } else if (method == 'stopTest') {
      const rec = getWebRecordInstanse();
      rec.stop();
      rec.getBlob(async (blob) => {
        const maxAge = 70 * 365 * 24 * 60 * 60; // 70年
        const now = Date.now();
        const audioName = `${now}_${Math.random().toString(36).substr(2)}.mp3`;
        const oss = await getOssInstanse();
        await oss.put(
          audioName,
          blob,
          {
            'Cache-Control': `max-age=${70 * 365 * 24 * 60 * 60}`,
            Expires: new Date(now + maxAge * 1000).toGMTString(),
            'Last-Modified': new Date().toGMTString(),
            'Content-type': `audio/mpeg`,
          }
        );
        const audioUrl = `${global.middleLayer.DOMAIN}${audioName}`;
        console.log(`上传的录音是：${audioUrl}`);

        const formData = new FormData();
        formData.append('audio', blob);
        formData.append("text", JSON.stringify(pubskyparms));
        var xhr = new XMLHttpRequest();
        xhr.open("post" , baseUrl + 'para.eval');
        xhr.setRequestHeader( "Request-Index" , "0");//Request-Index 固定为0
        xhr.send(formData);
        xhr.onreadystatechange = function () {
          if(xhr.readyState == 4 && xhr.status == 200){
            const res = JSON.parse(xhr.responseText);
            window.air.testCallBack({...res, audioUrl});
          }
        };
      });
    } else if (method == 'startRecord') {
      isSpeechToText = param.isSpeechToText;
      // 初始化参数
      if (isSpeechToText == 1) {
        initSkKouYuParms("", 'asr.rec');
      }
      const rec = getWebRecordInstanse();
      rec.start();
    } else if (method == 'stopRecord') {
      const rec = getWebRecordInstanse();
      rec.stop();
      rec.getBlob(async (blob) => {
        const maxAge = 70 * 365 * 24 * 60 * 60; // 70年
        const now = Date.now();
        const audioName = `${now}_${Math.random().toString(36).substr(2)}.mp3`;
        const oss = await getOssInstanse();
        await oss.put(
          audioName,
          blob,
          {
            'Cache-Control': `max-age=${70 * 365 * 24 * 60 * 60}`,
            Expires: new Date(now + maxAge * 1000).toGMTString(),
            'Last-Modified': new Date().toGMTString(),
            'Content-type': `audio/mpeg`,
          }
        );
        const audioUrl = `${global.middleLayer.DOMAIN}${audioName}`;
        console.log(`上传的录音是：${audioUrl}`);

        if (isSpeechToText == 1) {
          const formData = new FormData();
          formData.append('audio', blob);
          formData.append("text", JSON.stringify(pubskyparms));
          var xhr = new XMLHttpRequest();
          xhr.open("post" , baseUrl + 'asr.rec');
          xhr.setRequestHeader( "Request-Index" , "0");//Request-Index 固定为0
          xhr.send(formData);
          xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && xhr.status == 200){
              const res = JSON.parse(xhr.responseText);
              window.air.recordCallBack({text: res.result.recognition, audioUrl, ...res});
              isSpeechToText = 0;
            }
          };
        } else {
          window.air.recordCallBack({audioUrl});
        }
      });
    } else if (method == 'startBuyToAppStore') {
      window.air.startBuyToAppStoreCallBack({productid: 1, puid: 22, receiptData: "HelloWorld", error: ""});
    } else{
      console.error(`${method}方法还没有Mock数据，请联系技术支持人员添加`);
    }
  } else {
    // 其他环境
    if(method == 'getEngineInfo'){
      window.air.getEngineInfoCallback({isDev: 1, uuid: 'debug-xxxxxx-xxxxxx'});
    }
  }
}
