/**
 * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
 * Reserved. MIT License  (https://opensource.org/licenses/MIT)
 */

/* 2021-2023 by zhaoming,mali aihealthx.com */

export default function WebSocketConnectMethod(config) {
  //定义socket连接方法类
  let speechSokt;
  let connKeeperID;

  let msgHandle = config.msgHandle;
  let stateHandle = config.stateHandle;

  this.wsStart = function () {
    let Uri = config.url; //"wss://111.205.137.58:5821/wss/" //设置wss asr online接口地址 如 wss://X.X.X.X:port/wss/
    if (Uri.match(/wss:\S*|ws:\S*/)) {
      console.log('Uri' + Uri);
    } else {
      alert('请检查wss地址正确性');
      return 0;
    }

    if ('WebSocket' in window) {
      speechSokt = new WebSocket(Uri); // 定义socket连接对象
      speechSokt.onopen = function (e) {
        onOpen(e);
      }; // 定义响应函数
      speechSokt.onclose = function (e) {
        console.log('onclose ws!');
        //speechSokt.close();
        onClose(e);
      };
      speechSokt.onmessage = function (e) {
        onMessage(e);
      };
      speechSokt.onerror = function (e) {
        onError(e);
      };
      return 1;
    } else {
      alert('当前浏览器不支持 WebSocket');
      return 0;
    }
  };

  // 定义停止与发送函数
  this.wsStop = function () {
    if (speechSokt !== undefined) {
      console.log('stop ws!');
      speechSokt.close();
    }
  };

  this.wsSend = function (oneData) {
    if (speechSokt === undefined) return;
    if (speechSokt.readyState === 1) {
      // 0:CONNECTING, 1:OPEN, 2:CLOSING, 3:CLOSED
      speechSokt.send(oneData);
    }
  };

  // SOCEKT连接中的消息与状态响应
  function onOpen(e) {
    // 发送json
    let chunk_size = [5, 10, 5];
    let request = {
      chunk_interval: 10,
      chunk_size: chunk_size,
      hotwords: '{"阿里巴巴":20,"hello world":40}',
      is_speaking: true,
      itn: false,
      mode: '2pass',
      wav_name: 'h5'
    };
    console.log(JSON.stringify(request));
    speechSokt.send(JSON.stringify(request));
    console.log('连接成功');
    stateHandle(0);
  }

  function onClose(e) {
    console.log(e);
    stateHandle(1);
  }

  function onMessage(e) {
    msgHandle(e);
  }

  function onError(e) {
    console.log(e);
    stateHandle(2);
  }
}
