import { browser, getRandomKey } from '../common/common'
/**
 *
 * 目前已支持API
 *
 * openWebView
 *
 * openMusicEvaluate 乐团课评价时调用
 * backRefreshPage 返回时刷新页面
 *
 */

const loop = () => {}

const calls = {}

const browserInfo = browser()
if (browserInfo.isApp) {
  window.addEventListener('message', evt => {
    try {
      const data = evt.data ? typeof evt.data === 'object' ? evt.data : JSON.parse(evt.data) : {}
      const uuid = data.content.uuid || data.uuid
      try {
        if (data.content) {
          data.content = JSON.parse(data.content)
        }
      } catch (error) {}
      if (!uuid) {
        const keys = Object.keys(calls).filter(key => key.indexOf(data.api) === 0)
        for (const key of keys) {
          const callback = calls[key] || loop
          callback(data)
        }
        return
      }
      const callback = calls[data.content.uuid || data.uuid || (data.api + data.uuid)] || loop
      callback(data)
    } catch (error) {
      console.error('通信消息解析错误', error)
    }
  })
}

const instance = window.DAYA || (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.DAYA)

export const postMessage = (data, callback) => {
  if (browserInfo.isApp) {
    const uuid = getRandomKey()
    calls[uuid] = callback || loop
    data.content = data.content ? {...data.content, uuid} : {uuid}
    instance.postMessage(JSON.stringify(data))
  }
}

export const listenerMessage = (api, callback) => {
  if (browserInfo.isApp) {
    const uuid = api + getRandomKey()
    calls[uuid] = callback || loop
  }
}
