const SSH=require('./ssh');
const util=require('util');
const Logger = require('../logs/clsLogger').clsLogger;
const logger = new Logger();
const SSHManager=class SSHManager {
    constructor({push} = {}) {
        this.push = push;
        this.Clients = {};
        this.push.on(this.push.eventsTypes.NotifyEvent, (p) => {
            let nclientID = p.getNotifyingClient().getClientId();
            if (!nclientID)return;
            try{
            let msg = JSON.parse(JSON.parse(p.getDataJson()));
            let command = parseInt(p.getTag());
            switch (command){
                case this.push._pushFunctions.ServerSendConnect:
                    this.findAndAddClient(nclientID);
                    break;
                case this.push._pushFunctions.ServerSendSSHCmd:
                    this.processMsg(nclientID,msg);
                    break;
                case this.push._pushFunctions.ServerSendDisconnect:
                    this.disconnectClient(nclientID);
                    break;
            }
            }
            catch(e){}

        })

    }

    disconnectClient(clientId){
        logger.SSHTerminal(`disconnecting client: ${clientId}`);
        let client=this.Clients[clientId];
        if (client){
            client.close();
            delete this.Clients[clientId];
            logger.SSHTerminal(`client ${clientId} disconnected`)
        }
    }
    processMsg(clientId,msg){
        this.findAndAddClient(clientId);
        let client=this.Clients[clientId];
        if (client){
            client.write(msg)
        }
    }

    findAndAddClient(clientId){
        if (!this.Clients[clientId]){
            logger.SSHTerminal(`creating new session for ${clientId}`);
            let ssh=new SSH({clientID:clientId,push:this.push});
            this.Clients[clientId]=ssh;
            ssh.on('close',(cid)=>{
                logger.SSHTerminal(`close event received for ${cid}`);
                let Client=this.Clients[cid];
                if (Client){
                    Client.close();
                    delete this.Clients[cid];
                    logger.SSHTerminal(`client:${cid} disconnected and removed`);
                }
            })
        }
    }


};


const EventEmitter = require('events').EventEmitter;
util.inherits(SSHManager, EventEmitter);

module.exports = SSHManager;