/*Canopy - The next generation of stoner streaming software
Copyright (C) 2024-2025 Rainbownapkin and the TTN Community

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.*/

//local includes
const loggerUtils = require("../utils/loggerUtils");
const socketUtils = require("../utils/socketUtils");

/**
 * Class containg global server-side logic for handling namespaces outside of the main one
 */
class auxServer{
    /**
     * Instantiates object containing global server-side private message relay logic
     * @param {Socket.io} io - Socket.io server instanced passed down from server.js 
     * @param {channelManager} chanServer - Sister channel management server object
     */
    constructor(io, chanServer, namespace){
        /**
         * Socket.io server instance passed down from server.js
         */
        this.io = io;

        /**
         * Sister channel management server object
         */
        this.chanServer = chanServer;

        /**
         * Socket.io server namespace for handling messaging
         */
        this.namespace = io.of(namespace);

        //Handle connections from private messaging namespace
        this.namespace.on("connection", this.handleConnection.bind(this) );
    }

    /**
     * Handles global server-side initialization for new connections to aux server
     * @param {Socket} socket - Requesting Socket
     */
    async handleConnection(socket, lite = true){
        try{
            //Define empty value to hold result
            let result = null;

            //ensure unbanned ip and valid CSRF token
            if(!(await socketUtils.validateSocket(socket))){
                socket.disconnect();
                return null;
            }

            if(lite){
                result = await socketUtils.authSocketLite(socket);
            }else{
                result = await socketUtils.authSocket(socket);
            }

            //If the socket wasn't authorized
            if(result == null){
                socket.disconnect();
                return null;
            }

            return result;
        }catch(err){
            //Flip a table if something fucks up
            return loggerUtils.socketCriticalExceptionHandler(socket, err);
        } 
    }

    defineListeners(socket){
    }
}

module.exports = auxServer;