import { client, xml } from "@xmpp/client"
import uuid from "uuid"
import debug from "@xmpp/debug"

export default class XMPPConnection extends EventTarget {
   joinChannel(channel) {
    const channelIdent = `${channel}@conference.xmpp.lets-draw.live/${this.username}`
    const presence = xml(
      "presence",
      { to: channelIdent },
      xml("x", { xmlns: "http://jabber.org/protocol/muc" }),
    )
 this.sendOrQueue(presence)
  }

   sendOrQueue(message) {
    if (this.online) {
      this.xmpp.send(message)
    } else {
      this.queue.push(message)
    }
}

   sendChannelMessage(channel, message) {
    const channelIdent = `${channel}@conference.xmpp.lets-draw.live`
    const wrappedMessage = xml(
      "message",
      {
        type: "groupchat",
        to: channelIdent,
      },
      xml("body", {}, message),
    )

     this.sendOrQueue(wrappedMessage)
  }

  constructor() {
    super()

    this.username = uuid.v4().toString()
    this.online = false
    this.queue = []

    const xmpp = client({
      service: "wss://xmpp.lets-draw.live:5281/xmpp-websocket",
      domain: "xmpp.lets-draw.live",
      username: "beartest",
      password: "beartest",
    })

    this.xmpp = xmpp
debug(xmpp, true)

xmpp.on('status', status => {
  console.debug('🛈', 'status', status)
})
xmpp.on('input', input => {
  console.debug('⮈', input)
})
xmpp.on('output', output => {
  console.debug('⮊', output)
})

    xmpp.on("error", (err) => {
      console.error("❌", err.toString())
    })

    xmpp.on("offline", () => {
      this.online = false
    })

    xmpp.on("stanza", (stanza) => {
      if (stanza.is("message")) {
        this.dispatchEvent(
          new CustomEvent("stanza", {
            detail: stanza,
          }),
        )
      }
    })

    xmpp.on("online", async (address) => {
      /*eslint no-unused-vars: ["error", { "args": "none" }]*/

      // Makes itself available
      await xmpp.send(xml("presence"))

      this.online = true

      for (const message of this.queue) {
        await this.xmpp.send(message)
      }
    })

    xmpp.start().catch(console.error)
     this.joinChannel("imperial")

  }

  sneakilySendTheOtherTeamOur(secrets) {
      this.sendChannelMessage("imperial", secrets)
  }
}