/* 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

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

        webrtc.connection.on("message", (data) =>
          console.log("socket.io", data),
        )
      })

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

        for (let f of this.userEventListeners) {
          f({ action: "userID", id: id })
        }

        this.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) => {
        console.log(
          "createdPeer",
          peer.id,
          this.webrtc.getPeers().map((peer) => peer.id),
        )
        this.userJoined(peer.id, "master")
      })

      webrtc.on("receivedPeerData", (type, message, peer) => {
        if (message.type !== "update")
          console.log(
            "receivedData",
            peer.id,
            message,
            this.webrtc.getPeers().map((peer) => peer.id),
          )
        this.receiveMessage(peer.id, message)
      })

      webrtc.on("channelClose", (dataChannel, peer) => {
        console.log(
          "removedPeer",
          peer.id,
          this.webrtc.getPeers().map((peer) => peer.id),
        )
        this.userLeft(peer.id)
      })
    }

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

    disconnect() {
      this.webrtc.quit()

      super.disconnect()
    }

    reconnect() {
      this.initialiseConnection()

      super.reconnect()
    }

    send(uid, message) {
      console.log(
        "send",
        uid,
        message,
        this.webrtc.getPeers().map((peer) => peer.id),
      )
      this.webrtc.whisper(this.webrtc.getPeerById(uid), "y-js", message)
    }

    broadcast(message) {
      if (message.type !== "update")
        console.log(
          "broadcast",
          message,
          this.webrtc.getPeers().map((peer) => peer.id),
        )
      this.webrtc.shout("y-js", message)
    }

    isDisconnected() {
      return false
    }
  }

  Y.extend("webrtc", WebRTC)
}

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