/* global Y */
"use strict"

import LioWebRTC from "liowebrtc"

function extend(Y) {
  class WebRTC extends Y.AbstractConnector {
    constructor(y, options) {
      if (options === undefined) {
        throw new Error("Options must not be undefined!")
      }

      options.role = "slave"
      super(y, options)
      this.webrtcOptions = options

      this.initialiseConnection()
    }

    initialiseConnection() {
      const webrtc = new LioWebRTC({
        url: this.webrtcOptions.url,
        dataOnly: true,
        network: {
          minPeers: 4,
          maxPeers: 8,
        },
      })

      this.webrtc = webrtc
      const self = this

      webrtc.on("ready", () => {
        webrtc.joinRoom(self.webrtcOptions.room)
      })

      webrtc.on("joinedRoom", () => {
        const id = webrtc.getMyId()

        for (var f of self.userEventListeners) {
          f({ action: "userID", id: id })
        }

        self.setUserId(id)
      })

      // Cannot use createdPeer here as y-js will then try to send data before the channel is open
      webrtc.on("channelOpen", (dataChannel, peer) => {
        self.userJoined(peer.id, "master")
      })

      webrtc.on("receivedPeerData", (type, message, peer) => {
        self.receiveMessage(peer.id, message)
      })

      webrtc.on("removedPeer", (peer) => {
        self.userLeft(peer.id)
      })
    }

    connectToPeer(/*uid*/) {
      // currently deprecated
    }

    disconnect() {
      this.webrtc.quit()

      super.disconnect()
    }

    reconnect() {
      this.initialiseConnection()

      super.reconnect()
    }

    send(uid, message) {
      this.webrtc.whisper(this.webrtc.getPeerById(uid), "y-js", message)
    }

    broadcast(message) {
      this.webrtc.shout("y-js", message)
    }

    isDisconnected() {
      return false
    }
  }

  Y.extend("webrtc", WebRTC)
}

export default extend
if (typeof Y !== "undefined") {
  extend(Y)
}