/**
 * Template Socket.IO Connection Middleware for uibuilder.
 * UPDATED: 2022-04-01
 *
 * NOTES & WARNINGS:
 *   1) This function is only called ONCE - when a new client connects. So any authentication/security processing is limited
 *      because you cannot use this to, for example, timeout/extend a session without further server processing of incoming messages.
 *      However, see the sioUse.js and sioMsgOut.js middlewares for per-msg handling.
 *   2) Failing to either return or call `next()` will mean that your clients will never connect.
 *   3) An error in this function will probably cause Node-RED to fail to start at all.
 *   4) You have to restart Node-RED if you change this file.
 *   5) To use for authentication/authorisation with Express and sio connection middleware, create a common node.js module.
 *
 * Allows custom processing for authentication, session management, connection validation, logging, rate limiting, etc.
 * 
 * see also: uibRoot/.config/sioUse.js & sioMsgOut.js
 *           https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#websocket-implementation-hints
 * 
 * @param {*} socket Socket.IO socket object
 * @param {function} next The callback to hand off to the next middleware
 */
function sioMw(socket, next) {
    // Some SIO related info that might be useful in security checks
    console.log('== [sioMiddleware.js] ====================')
    console.log('New client connected to Namespace')
    console.log('--socket.request.connection.remoteAddress--', socket.request.connection.remoteAddress)
    console.log('--socket id--', socket.id)
    // Added by uibuilder when Namespace is created by uibuilder node instance - Note also that socket.nsp.log can be used to output to the Node-RED log
    console.log('--socket namespace metadata (server)--', {
        name: socket.nsp.name,
        url: socket.nsp.url,
        nodeId: socket.nsp.nodeId,
        useSecurity: socket.nsp.useSecurity,
    })
    //console.log('--socket handshake--', socket.handshake)
    //console.log('--socket properties--', Object.keys(socket))
    // Show the client id (set by uibuilder ExpressJS middleware)
    console.log('--client id handshake.auth--', socket.handshake.auth.clientId)
    console.log('--client id in custom header (polling only)--', socket.handshake.headers['x-clientid'])
    console.log('==========================================\n ')

    // Simplistic auth example
    let auth = true
    if (auth !== true) {
        socket.nsp.log.error(`[uibuilder:sioMiddleware.js] - Authentication error, client disconnected - ID: ${socket.id}`)
        return next (new Error(`[uibuilder:sioMiddleware.js] - Authentication error, client disconnected - ID: ${socket.id}` ))
    }

    return next()

} // Remember to end with a `next()` statement or nothing will work.

module.exports = sioMw