/*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/>.*/

//Config
const config = require('../../../config.json');

//Local Imports
const channelModel = require('../../schemas/channel/channelSchema');
const emoteModel = require('../../schemas/emoteSchema');
const socketUtils = require('../../utils/socketUtils');
const loggerUtils = require('../../utils/loggerUtils');
const presenceUtils = require('../../utils/presenceUtils');
const activeChannel = require('./activeChannel');
const chatHandler = require('./chatHandler');
const queueBroadcastManager = require('./media/queueBroadcastManager');

/**
 * Class containing global server-side channel connection management logic
 */
class channelManager{
    /**
     * Instantiates object containing global server-side channel conection management logic
     * @param {Socket.io} io - Socket.io server instanced passed down from server.js 
     */
    constructor(io){
        /**
         * Socket.io server instance passed down from server.js
         */
        this.io = io;

        /**
         * Map containing all active channels running on the server
         */
        this.activeChannels = new Map;

        /**
         * Map containing all active users. This may be redundant, however it improves preformance for user-specific inter-channel functionality
         */
        this.activeUsers = new Map;

        /**
         * Global Chat Handler Object
         */
        this.chatHandler = new chatHandler(this);

        /**
         * Global Chat Handler Object
         */
        this.chatHandler = new chatHandler(this);

        /**
         * Global Auxiliary Server for Authenticated Queue Metadata Brodcasting 
         */
        this.queueBroadcastManager = new queueBroadcastManager(this.io, this)

        //Handle connections from socket.io
        io.on("connection", this.handleConnection.bind(this) );
    }

    /**
     * Handles global server-side initialization for new connections to any channel
     * @param {Socket} socket - Requesting Socket
     */
    async handleConnection(socket){
        try{
            //ensure unbanned ip and valid CSRF token
            if(!(await socketUtils.validateSocket(socket))){
                socket.disconnect();
                return;
            }

            //Prevent logged out connections and authenticate socket
            if(socket.request.session.user != null){
                //Authenticate socket
                const userDB = await socketUtils.authSocket(socket);

                //Get the active channel based on the socket
                var {activeChan, chanDB} = await this.getActiveChan(socket);

                //Check for chan ban
                const ban = await chanDB.checkBanByUserDoc(userDB);
                if(ban != null){
                    //Toss out banned user's
                    if(ban.expirationDays < 0){
                        socket.emit("kick", {type: "kicked", reason: "You have been permanently banned from this channel!"});
                    }else{
                        socket.emit("kick", {type: "kicked", reason: `You have been temporarily banned from this channel, and will be unbanned in ${ban.getDaysUntilExpiration()} day(s)!`});
                    }
                    socket.disconnect();
                    return;
                }

                //Connection accepted past this point

                //Define listeners for inter-channel classes
                this.defineListeners(socket);
                this.chatHandler.defineListeners(socket);

                //Hand off the connection to it's given active channel object
                //Lil' hacky to pass chanDB like that, but why double up on DB calls?
                const activeUser = await activeChan.handleConnection(userDB, chanDB, socket);
                
                //Pull status from server-wide activeUsers map
                let status = this.activeUsers.get(activeUser.user);

                //If this user isn't connected anywhere else
                if(status == null){
                    //initiate the entry
                    this.activeUsers.set(activeUser.user, [activeUser]);
                //otherwise
                }else{
                    //Push user to array by default
                    let pushUser = true;

                    //For each active connection within the status map
                    for(let curUser of status){
                        //If we're already listing this active user (we're splitting a user connection amongst several sockets)
                        if(curUser.channel.name == activeUser.channel.name){
                            //don't need to push it again
                            pushUser = false;
                        }
                    }

                    //if the user is flagged as un-added
                    if(pushUser){
                        //Add their connection object into the status array we pulled
                        status.push(activeUser);

                        //Set status entry to updated array
                        this.activeUsers.set(activeUser.set, status);
                    }
                }


            }else{
                //Toss out anon's
                socket.emit("kick", {type: "disconnected", reason: "You must log-in to join this channel!"});
                socket.disconnect();
                return;
            }
        }catch(err){
            //Flip a table if something fucks up
            return loggerUtils.socketCriticalExceptionHandler(socket, err);
        } 
    } 

    /**
     * Gets active channel from a given socket
     * @param {Socket} socket - Socket to check
     * @returns {Object} Object containing users active channel name and channel document object
     */
    async getActiveChan(socket){
        socket.chan = socketUtils.getChannelName(socket);
        const chanDB = (await channelModel.findOne({name: socket.chan}));

        //Check if channel exists
        if(chanDB == null){
            throw loggerUtils.exceptionSmith("Channel not found", "validation");
        }

        //Check if current channel is active
        var activeChan = this.activeChannels.get(socket.chan);

        if(!activeChan){
            //If not, make it so
            activeChan = new activeChannel(this, chanDB);
            this.activeChannels.set(socket.chan, activeChan);
        }

        //Return whatever the active channel is (new or old)
        return {activeChan, chanDB};
    }

    /**
     * Define Global Server-Side socket event listeners
     * @param {Socket} socket - Socket to check
     */
    defineListeners(socket){
        //Socket Listeners
        socket.conn.on("close", (reason) => {this.handleDisconnect(socket, reason)});
    }

    /**
     * Global server-side logic for handling disconncted sockets
     * @param {Socket} socket - Socket to check
     * @param {String} reason - Reason for disconnection
     */
    handleDisconnect(socket, reason){
        var activeChan = this.activeChannels.get(socket.chan);
        activeChan.handleDisconnect(socket, reason);
    }

    /**
     * Handles a disconnection event for a single active user within a given channel (when all sockets disconnect)
     * @param {connectedUser} userObj - Connected user object to handle disconnection of
     */
    handleUserDisconnect(userObj){
        //Create array to hold
        let stillConnected = [];

        //Crawl through all known user connections
        this.crawlConnections(userObj.user, (curUser)=>{
            //If we have a matching username from a different channel
            if(curUser.user == userObj.user && userObj.channel.name != curUser.channel.name){
                //Keep current user
                stillConnected.push(curUser);
            }
        });

        //If we have anyone left
        if(stillConnected.length > 0){
            //save the remainder to the status map, otherwise unset the value.
            this.activeUsers.set(userObj.user, stillConnected);
        //Otherwise
        }else{
            //Delete the user from the status map
            this.activeUsers.delete(userObj.user);

            //Mark last disconnection as user activity, as they'll no longer be marked as streaming.
            presenceUtils.handlePresence(userObj.user);
        }
    }

    /**
     * Pulls user information by socket
     * @param {Socket} socket - Socket to check
     * @return returns related user info
     */
    getSocketInfo(socket){
        const channel = this.activeChannels.get(socket.chan);
        return channel.userList.get(socket.user.user);
    }

    /**
     * Pulls user information by socket
     * @param {Socket} socket - Socket to check
     * @return returns related user info
     */
    getConnectedChannels(socket){
        //Create a list to hold connected channels
        var chanList = [];

        //For each channel
        this.activeChannels.forEach((channel) => {
            //Check and see if the user is connected
            const foundUser = channel.userList.get(socket.user.user);

            //If we found a user and this channel hasn't been added to the list
            if(foundUser){
                chanList.push(channel);
            }
        });

        //return the channels this user is connected to
        return chanList;
    }

    /**
     * Iterates through connections by a given username, and runs them through a given callback function/method
     * @param {String} user - Username to crawl connections against
     * @param {Function} cb - Callback function to run active connections of a given user against
     */
    crawlConnections(user, cb){
        //Pull connection list from status map
        const list = this.activeUsers.get(user);

        //If we have active connections
        if(list != null){
            //For each connection
            for(let user of list){
                //Run the callback against it
                cb(user);
            }
        }

    }

    /**
     * Iterates through connections by a given username, and runs them through a given callback function/method
     * This function is deprecated. Instead use channelManager.activeUsers.get(user)
     * @param {String} user - Username to crawl connections against
     * @param {Function} cb - Callback function to run active connections of a given user against
     */
    getConnections(user){
        const connections = this.activeUsers.get(user);

        //return connects
        return connections;
    }

    /**
     * Kicks a user from all channels by username
     * @param {String} user - Username to kick from the server
     * @param {String} reason - Reason for kick
     */
    kickConnections(user, reason){
        //crawl through connections and kick user
        this.crawlConnections(user,(foundUser)=>{foundUser.disconnect(reason)});
    }

    /**
     * Broadcast global emote list
     */
    async broadcastSiteEmotes(){
        //Get emote list from DB
        const emoteList = await emoteModel.getEmotes();

        //Broadcast that sumbitch
        this.io.sockets.emit('siteEmotes', emoteList);
    }
}

module.exports = channelManager;