'use strict'
!(function(require, directRequire) {
  'use strict'
  var a = Math.round
  Object.defineProperty(exports, '__esModule', { value: !0 })
  const b = require('eventemitter3'),
    c = require('./ce02bd5f4368747c4e2fff84ed0fc0de.js'),
    d = require('./a148d3a11fd5268109e21fb40c9d527b.js'),
    e = require('./46d7303eb986fa402d60bf5e929aa077.js'),
    f = require('./56a764ae9cb4336bf6babe1c1da0275b.js'),
    g = f.default('[localmessager]'),
    h = e.logInvoke(g)
  var i
  ;(function(a) {
    ;(a[(a.Dead = -1)] = 'Dead'),
      (a[(a.Unintialized = 0)] = 'Unintialized'),
      (a[(a.Disconnected = 1)] = 'Disconnected'),
      (a[(a.Waiting = 4)] = 'Waiting'),
      (a[(a.ActiveIdle = 7)] = 'ActiveIdle')
  })((i = exports.LocalMessagerStatus || (exports.LocalMessagerStatus = {})))
  class j extends b.EventEmitter {
    constructor(a) {
      super(),
        (this.roomInfo = null),
        (this.debugServer = null),
        (this.status = i.Unintialized),
        (this.managedSeq = 0),
        (this.receivedSeq = 0),
        (this.managedDebugTimestamp = NaN),
        (this.debugMessagesToSend = []),
        (this.receivedDebugMessages = []),
        (this.debugMessagesCollectionTimeout = void 0),
        (this.lastDebugMessageSendTimestamp = Date.now()),
        (this._destroyed = !1),
        (this._inited = !1),
        (this.eventListeners = []),
        (this.outDebugMessageCount = 0),
        (this.inDebugMessageCount = 0),
        (this._lastOutDebugMessageCount = 0),
        (this._lastInDebugMessageCount = 0),
        (this._lastInCalcTime = Date.now()),
        (this._lastOutCalcTime = Date.now()),
        (this.autoLoopingTimeout = void 0),
        (global.lm = this),
        (this.roomInfo = a.roomInfo),
        (this.debugServerPort = a.debugServerPort),
        (this.debugServer = a.debugServer)
    }
    get inBytesCount() {
      return this.debugServer ? this.debugServer.inBytesCount : 0
    }
    get outBytesCount() {
      return this.debugServer ? this.debugServer.outBytesCount : 0
    }
    get unconfirmedMessagesCount() {
      return this.debugServer
        ? this.debugServer.archivedDebugMessages.length
        : 0
    }
    get inDebugMessageSpeed() {
      const b = Date.now(),
        c = (b - this._lastInCalcTime) / 1e3
      this._lastInCalcTime = b
      const d = this.inDebugMessageCount - this._lastInDebugMessageCount
      return (
        (this._lastInDebugMessageCount = this.inDebugMessageCount),
        0 <= d ? a(d / c) : 0
      )
    }
    get outDebugMessageSpeed() {
      const b = Date.now(),
        c = (b - this._lastOutCalcTime) / 1e3
      this._lastOutCalcTime = b
      const d = this.outDebugMessageCount - this._lastOutDebugMessageCount
      return (
        (this._lastOutDebugMessageCount = this.outDebugMessageCount),
        0 <= d ? a(d / c) : 0
      )
    }
    init() {
      if (this._destroyed)
        return void g.w('cannot init destroyed local messager')
      if (this._inited) return void g.w('already inited')
      if (!this.debugServer) return void g.w('debugServer not ready')
      this._inited = !0
      const a = this.debugServer,
        b = this.onDebugServerStatusChange.bind(this),
        c = this.onDebugServerEvent.bind(this),
        d = this.onDebugServerAccident.bind(this),
        e = this.onDebugServerClientReady.bind(this),
        f = this.onRemoteDebugReady.bind(this),
        h = this.onDebugServerDebugMessages.bind(this),
        j = this.onDebugServerDestroy.bind(this),
        k = this.onDebugServerEnd.bind(this)
      this.eventListeners.push(['statuschange', b]),
        this.eventListeners.push(['event', c]),
        this.eventListeners.push(['accident', d]),
        this.eventListeners.push(['clientready', e]),
        this.eventListeners.push(['remotedebugready', f]),
        this.eventListeners.push(['debugmessages', h]),
        this.eventListeners.push(['destroy', j]),
        this.eventListeners.push(['debugend', k])
      for (const b of this.eventListeners) a.on(b[0], b[1])
      this.debugServer.setDevtool(this), this.setStatus(i.Disconnected)
    }
    setStatus(a) {
      this.status !== a &&
        ((this.status = a), this.emit('statuschange', this.status))
    }
    getRoomInfo() {
      return this.roomInfo
        ? this.roomInfo
        : (g.w('invalid room info', this.roomInfo), {})
    }
    onDebugServerClientReady() {
      this.debugServer &&
        (this.setStatus(i.Waiting), this.debugServer.devtoolJoinRoom())
    }
    onRemoteDebugReady() {
      this.setStatus(i.ActiveIdle), this.enableAutoLoop()
    }
    enableAutoLoop() {
      this.autoLoopingTimeout &&
        (g.i('already auto looping'), clearTimeout(this.autoLoopingTimeout))
      const a = () => {
        this.emit('statuschange', this.status),
          (this.autoLoopingTimeout = setTimeout(a, 2e3))
      }
      this.autoLoopingTimeout = setTimeout(a, 0)
    }
    onDebugServerStatusChange() {
      this.emit('statuschange', this.status)
    }
    onDebugServerEvent(a) {
      this.emit('event', a)
    }
    onDebugServerAccident(a) {
      this.emit('accident', a)
    }
    getBaseRequestTemplate() {
      return { clientversion: e.clientVersion }
    }
    sendDebugMessage(a, b, c, e) {
      var f = Math.max
      const g = {
        seq: ++this.managedSeq,
        delay: 0,
        category: b,
        data: a,
        _len: (c && c.len) || 0,
        compress_algo: e
      }
      if (b !== d.DebugMessageCategory.Ping) {
        const a = c && 'number' == typeof c.timestamp ? c.timestamp : Date.now()
        ;(g.delay = isNaN(this.managedDebugTimestamp)
          ? 0
          : f(0, a - this.managedDebugTimestamp)),
          (this.managedDebugTimestamp = f(this.managedDebugTimestamp, a))
      }
      this.debugMessagesToSend.push(g), this.startCollectDebugMessages()
    }
    startCollectDebugMessages(a = 0) {
      this.debugMessagesCollectionTimeout ||
        (a && Date.now() - this.lastDebugMessageSendTimestamp > a && (a = 0),
        (this.debugMessagesCollectionTimeout = setTimeout(() => {
          this.sendDebugMessagesImmediately()
        }, a)))
    }
    sendDebugMessagesImmediately() {
      if (
        (clearTimeout(this.debugMessagesCollectionTimeout),
        (this.debugMessagesCollectionTimeout = void 0),
        !this.debugServer)
      )
        return void g.w('debug server not ready send debug messages')
      const a = this.debugMessagesToSend
      if (((this.debugMessagesToSend = []), 1 > a.length))
        return void g.i('nothing new to send')
      this.debugServer.devtoolSendDebugMessages(a),
        (this.outDebugMessageCount += a.length)
      const b = Date.now()
      this.lastDebugMessageSendTimestamp = b
    }
    onDebugServerDebugMessages(a) {
      if (a && !(1 > a.length)) {
        ;(this.inDebugMessageCount += a.length),
          this.receivedDebugMessages.push(...a),
          this.receivedDebugMessages.sort(c.sorterForDebugMessage)
        for (let a = 0; a < this.receivedDebugMessages.length; a++) {
          const b = this.receivedDebugMessages[a]
          if (!(b.seq <= this.receivedSeq)) {
            if (b.seq !== this.receivedSeq + 1) {
              g.w(
                'received seq',
                b.seq,
                'larger than received seq',
                this.receivedSeq
              )
              break
            }
            ++this.receivedSeq, this.emit('debugmessage', b)
          }
        }
        this.receivedDebugMessages = this.receivedDebugMessages.filter(
          a => a.seq > this.receivedSeq
        )
      }
    }
    onDebugServerDestroy() {
      this.destroy()
    }
    onDebugServerEnd() {
      this.emit('event', { type: 'end', kind: 'event' }),
        this.setStatus(i.Disconnected),
        this.autoLoopingTimeout &&
          (clearTimeout(this.autoLoopingTimeout),
          (this.autoLoopingTimeout = void 0))
    }
    destroy() {
      if (!this._destroyed) {
        if (
          (this.autoLoopingTimeout &&
            (clearTimeout(this.autoLoopingTimeout),
            (this.autoLoopingTimeout = void 0)),
          this.setStatus(i.Dead),
          (this._destroyed = !0),
          this.debugServer)
        ) {
          this.debugServer.devtoolQuitRoom()
          for (const a of this.eventListeners)
            this.debugServer.removeListener(a[0], a[1])
          this.eventListeners = []
        }
        this.emit('destroy')
      }
    }
    onAskForRetry() {}
  }
  exports.LocalMessager = j
})(require('lazyload'), require)
