import * as AgoraRTM from 'agora-rtm-sdk'
import * as EventEmitter from 'events'

export default class RTMClient extends EventEmitter {
  // on(arg0, arg1) {
  //   throw new Error("Method not implemented.");
  // }
  // clearState() {
  //   throw new Error("Method not implemented.");
  // }
  constructor () {
    super()
    this.channel = null
    this._logined = false
  }

  init (appId) {
    this.client = AgoraRTM.createInstance(appId)
    this.subscribeClientEvents()
  }

  // subscribe client events
  subscribeClientEvents () {
    const clientEvents = [
      'ConnectionStateChanged',
      'MessageFromPeer'
    ]
    clientEvents.forEach((eventName) => {
      this.client.on(eventName, (...args) => {
        console.log('emit ', eventName, ...args)
        // log event message
        this.emit(eventName, ...args)
      })
    })
  }

  // subscribe channel events
  subscribeChannelEvents () {
    const channelEvents = [
      'ChannelMessage',
      'MemberJoined',
      'MemberLeft'
    ]
    channelEvents.forEach((eventName) => {
      this.channel.on(eventName, (...args) => {
        this.emit(eventName, {args: args })
      })
    })
  }

  unSubscribeChannelEvents () {
    const channelEvents = [
      'ChannelMessage',
      'MemberJoined',
      'MemberLeft'
    ]
    channelEvents.forEach((eventName) => {
      this.channel.removeListener(eventName, (...args) => {

      })
    })
  }

  async login (accountName, token) {
    this.accountName = accountName
    return this.client.login({ uid: this.accountName, token })
  }

  async logout () {
    return this.client.logout()
  }

  async joinChannel (name) {
    console.log('joinChannel', name)
    this.channel = this.client.createChannel(name)
    this.subscribeChannelEvents()
    return this.channel.join()
  }

  async leaveChannel () {
    console.log('leaveChannel')
    this.unSubscribeChannelEvents()
    this.removeAllListeners()
    return this.channel.leave()
  }

  async getMembers () {
    return this.channel.getMembers()
  }

  async sendChannelMessage (text) {
    console.log('sendChannelMessage', text);
    return this.channel.sendMessage({ text })
  }

  async sendPeerMessage (text, peerId) {
    console.log('sendPeerMessage', text, peerId)
    return this.client.sendMessageToPeer({ text }, peerId.toString())
  }

  async queryPeersOnlineStatus (memberId) {
    console.log('queryPeersOnlineStatus', memberId)
    return this.client.queryPeersOnlineStatus([memberId])
  }
}