let EosHelper = {
  transfer: function (from, to, amount, memo, authority) {
    let action = 'transfer'
    let identity = { authorization: [`${from}@${authority}`] }
    if (self !== top) {
      return meeAction(action, [from, to, amount, memo, identity])
    } else {
      return window.EOS[action](from, to, amount, memo, identity)
    }
  },
  getCurrencyBalance: function (code, account, symbol = 'EOS') {
    let action = 'getCurrencyBalance'
    if (self !== top) {
      return meeAction(action, [code, account, symbol])
    } else {
      return window.EOS.getCurrencyBalance(code, account, symbol)
    }
  },
  async doSymbolTransfer (from, to, amount, memo, authority, contract) {
    let action = 'transfer'
    let identity = { authorization: [`${from}@${authority}`] }
    if (self !== top) {
      return meeAction(action, [from, to, amount, memo, identity], contract)
    } else {
      try {
        let _contract = await window.EOS.contract(contract)
        let res = await _contract[action](from, to, amount, memo, identity)
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  }
}

function meeAction (action, param, contract = '') {
  return window.postMessager.send({
    action: 'meechat:eosAction',
    data: { action, param, contract }
  })
}

export default EosHelper
