import IMSDK from './sdk'
import initListeners from "./listeners"

function IM() {
  // 消息类型
  const MESSAGETYPE = {
    IMAGE: 'image',
    TEXT: 'text',
    CARD: 'card',
  }

  const sdk = IMSDK()
  const listeners = initListeners()

  let sendPerson;
  let receivePerson;
  let timer;

  sdk.listen('onMessage', listeners.getListeners)

  return {
    MESSAGETYPE,
    init,
    listen: listeners.append,
    bindReceiver,
    connect: sdk.connect,
    sendMessage,
  }

  function bindReceiver(receiver) {
    receivePerson = receiver
  }

  function sendMessage(message, type = MESSAGETYPE.TEXT) {
    return sdk.send(wrapData(message, type))
  }

  function wrapData(message, messageType) {
    return JSON.stringify({
      sendPerson,
      receivePerson,
      message,
      messageType,
      createDate: new Date().valueOf(),
    })
  }

  function init(personId) {
    // eslint-disable-next-line no-undef
    const url = `${WSS_HOST}/wx/chat/${personId}`  

    sendPerson = personId

    if (timer) {
      clearInterval(timer)
    }

    timer = setInterval(() => {
      if (sdk.getState() !== sdk.STATE.OPEN) {
        im.connect({ url })
      } else {
        // sdk.send('ping')
      }
    }, 2 * 1000)
  }
}

const im = IM();
export default im;
