/**
 * High level WebSocket protocols implementation.
 * TODO - rewrite for UB5(linux) using node/go as microservice
 *
 * @module web-sockets
 * @memberOf module:@unitybase/ub
 * @author pavel.mash
 */
const EventEmitter = require('events').EventEmitter

const registeredWSProtocols = {}

/**
 * @classdesc
 *  Internal server-side WebSocket transport layer, which communicates with clients using low-level binding classes.
 *  Usually there is no need to use this class directly, it is better to use an instance of {@link JsonMessagesProtocol} from {@link UB.wsNotifier}
 *
 *  Server emits three types of event on the protocol level:
 *
 *   - `connect`, parameters are: ({WebSocketConnection} wsConn)
 *   - `disconnect`, parameters are: ({WebSocketConnection} wsConn, {string} closeReason, {Number} closeStatus) http://tools.ietf.org/html/rfc6455#section-7.4
 *   - `message`, parameters are: ({WebSocketConnection} wsConn, {String|ArrayBudder} message)
 * @param {object} props
 * @param {string} props.name
 * @param {string} props.handledAs
 * @class WebSocketTransport
 * @protected
 * @augments EventEmitter
 */
function WebSocketTransport (props) {
  // eslint-disable-next-line n/no-deprecated-api
  const wsBinding = process.binding('ub_ws')
  let wsProtocol, protocolIndex

  if (registeredWSProtocols.hasOwnProperty(props.name)) {
    wsProtocol = registeredWSProtocols[props.name]
  } else {
    if (process.isWebSocketServer) {
      wsProtocol = wsBinding.addProtocol(props)
      EventEmitter.call(wsProtocol)
      Object.assign(wsProtocol, EventEmitter.prototype)
      registeredWSProtocols[props.name] = wsProtocol
    } else {
      wsProtocol = wsBinding.retrieveProtocol(props)
      registeredWSProtocols[props.name] = wsProtocol // memorize null in case WS not supported
    }
    if (wsProtocol) {
      protocolIndex = wsProtocol.index
      /**
       * Returns the IDs of all the sessions with established WebSocket connections
       *
       * @memberOf WebSocketTransport
       * @param {number} userID uba_user identifier
       * @returns {Array<number>}
       */
      wsProtocol.getUserSessions = function (userID) {
        return wsBinding.getUserSessions(userID, protocolIndex)
      }
      /**
       * Send a data package to specified session ID.
       * Return true on success, false in case WS connection for the specified session is lost or closed/closing
       *
       * @param {number} sessionID
       * @param {string | object | ArrayBuffer} data
       * @returns {boolean}
       */
      wsProtocol.sendTo = function (sessionID, data) {
        return wsBinding.send(sessionID, protocolIndex, data)
      }

      /**
       *
       * @param {number} sessionID
       * @param {string} reason
       */
      wsProtocol.closeSession = function (sessionID, reason) {
        const data = (typeof reason === 'string') ? reason : JSON.stringify(reason)
        wsBinding.close(sessionID, protocolIndex, data)
      }

      /**
       * Send a data package to all protocol sessions.
       *
       * @param {string | object | ArrayBuffer} data
       */
      wsProtocol.broadcast = function (data) {
        wsBinding.broadcast(protocolIndex, data)
      }
    }
  }
  return wsProtocol
}

/**
 * @classdesc
 * Simple protocol for exchanging JSON commands.
 *
 * Each message transferred by a web socket is a JSON with two attributes
 *
 *      {command: {string}, params: {*}}
 *
 * Inside WebSocket threads, the class can be used to subscribe to messages arrived from clients
 * and assign handlers to it (if you need to receive web socket messages in server):

      const WebSockets = require('@unitybase/ub/modules/web-sockets')
      var wsNotifier = WebSockets.getWSNotifier()
      if (wsNotifier) {
        console.debug('Start subscribing to wsNotifier tsts_* events')
        wsNotifier.on('tst_echo', function (connection, params) {
          connection.send({
            command: 'tst_message',
            params: {from: connection.session.userID, message: params}
          })
        })
      }

 * Inside http threads can be used as follows:
 *
      const WebSockets = require('@unitybase/ub/modules/web-sockets')
      function notifyAboutNewRecord(rowID){
        let notifier = WebSockets.getWSNotifier()
        if (notifier) {
          //send message to ALL connected sessions
          notifier.broadcast('ub_entityModification', {action: 'insert', ID: rowID})

          //Send to specific user
          var userSessions = notifier.getUserSessions(Session.userID)
          userSessions.forEach(function(sessionID){
              notifier.sendCommand('test_command', sessionID, {action: 'inserted', ID: rowID})
          })
        }
      }
 *
 *  If WebSocket support are enabled in server config then instance of this protocol is accessible via {@link UB#wsNotifier UB.wsNotifier}
 * @class JsonMessagesProtocol
 * @param {string} namedAs The name of a resulting protocol
 * @augments EventEmitter
 */
function JsonMessagesProtocol (namedAs) {
  const me = this
  const _jsonProtocol = new WebSocketTransport({ name: namedAs, handledAs: 'Json' })

  /**
   * Send specified command to recipient. Return `true` if data has been successfully sent (no guaranty it is received by client)
   *
   * @param {string} command Command to send
   * @param {number} recipient User Session identifier
   * @param {*} params Any value
   * @returns {boolean}
   */
  this.sendCommand = function (command, recipient, params) {
    return _jsonProtocol.sendTo(recipient, { command, params })
  }

  /**
   * Returns the IDs of all the sessions with established WebSocket connections
   *
   * @param {number} userID User identifier (from uba_user)
   * @returns {Array<number>}
   */
  this.getUserSessions = function (userID) {
    return _jsonProtocol.getUserSessions(userID)
  }

  /**
   * Send specified command to all user sessions connected using this protocol
   *
   * @param {string} command Command to send
   * @param {*} params Any value
   */
  this.broadcast = function (command, params) {
    return _jsonProtocol.broadcast({ command, params })
  }

  if (process.isWebSocketServer) {
    EventEmitter.call(me)
    Object.assign(me, EventEmitter.prototype)

    /**
     * Handle incoming messages
     *
     * @protected
     * @param {WebSocketConnection} connection
     * @param {string | ArrayBuffer} rawData
     */
    me.onWSMessage = function (connection, rawData) {
      let msg

      console.debug('New WebSocket message from ', connection.session.id, rawData)
      try {
        msg = JSON.parse(rawData)
      } catch (err) {
        connection.send({ command: 'error', params: { description: 'Invalid params: ' + rawData } })
        return
      }
      if (!me.emit(msg.command, connection, msg.params)) {
        connection.send({ command: 'error', params: { description: 'Invalid command: ' + msg.command } })
      }
    }

    /**
     * @param {WebSocketConnection} connection
     * @protected
     */
    me.onWSConnect = function (connection) {
      console.debug('Web socket connected: ', connection.session.id)
      /**
       * Emited for {@link JsonMessagesProtocol} just after client is connected
       *
       * @event connect
       */
      me.emit('connect', connection)
      connection.send({
        command: 'accepted', params: { connectionID: connection.session.id }
      })
    }
    /**
     * @param {WebSocketConnection} connection
     * @param {string} reason
     * @param {number} status
     * @protected
     */
    me.onWSDisconnect = function (connection, reason, status) {
      console.debug('WS Disconnected ', connection.session.id, 'reason', reason, 'status', status)
      /**
       * Emited for {@link JsonMessagesProtocol} just after client is disconnected
       *
       * @event disconnect
       */
      me.emit('disconnect', connection, reason, status)
    }

    _jsonProtocol.on('connect', me.onWSConnect)
    _jsonProtocol.on('message', me.onWSMessage)
    _jsonProtocol.on('disconnect', me.onWSDisconnect)
  }
}

/**
 * Return array of currently registered WS protocol names
 *
 * @returns {Array<string>}
 */
function registeredProtocols () {
  // eslint-disable-next-line n/no-deprecated-api
  const wsBinding = process.binding('ub_ws')
  return wsBinding.getProtocols()
}

let _ubNotifierInstance = process.isWebSocketEnabled ? undefined : null

/**
 * Return an instance of {@link JsonMessagesProtocol} named `ubNotifier` for Server<->Client communication using WebSocket
 *
 * In case `ubNotifier` protocol is not registered during WebSocket thread initialization
 * or not configured in config - will return `null`
 *
 * Returned {@link JsonMessagesProtocol} instance methods is limited
 * by {@link WSProtocol#getUserSessions}, {@link WSProtocol#sendTo} and {@link WSProtocol#broadcast}
 *
 * See {@tutorial web_sockets} for detailed description
 *
 * @returns {JsonMessagesProtocol}
 */
function getWSNotifier () {
  if (_ubNotifierInstance || _ubNotifierInstance === null) { return _ubNotifierInstance }

  _ubNotifierInstance = new JsonMessagesProtocol('ubNotifier')
  return _ubNotifierInstance
}

module.exports = {
  protocols: {
    JsonMessages: JsonMessagesProtocol
  },
  Transport: WebSocketTransport,
  registeredProtocols,
  getWSNotifier
}