let pty = require('ptyw.js');
let util = require('util');
let _ = require('lodash');
const SSH = class SSH {
    constructor({push, clientID} = {}) {
        this.push = push;
        this.clientID = clientID;
        this.clientID = '3c5db0dd-6339-496c-9e47-a90c00ed3212';

        this.isConnected = true;
        this.push.on(this.push.eventsTypes.NotifyEvent, (p) => {
            let nclientID = p.getNotifyingClient().getClientId();
            if (nclientID) {
                //term.write()
                let msg = JSON.parse(JSON.parse(p.getDataJson()));
                term.write(msg);
            }
            let command = parseInt(p.getTag());

            //console.log('on notify tag:', command, ', data:', p.getDataJson());
        });

        this.msgqueue = [];


        let os = require('os');
        let cmder = 'cmd.exe';
        if (os.platform() == 'linux' || os.platform() == 'darwin') {
            cmder = 'bash'
        }

        let term = pty.spawn(cmder, [], {
            name: 'xterm-color',
            cols: 80,
            rows: 40,
            cwd: process.cwd(),
            env: process.env
        });
        this.term = term;

        term.write('ls -al\r\n');
        term.on('data', async (data) => {
            //console.log(data);
            //await this.push.NotifyClient(this.clientID,data,this.push._pushFunctions.ClientSendSSHExeResult)
            this.msgqueue.push(data)
        });

        this.processQueue();

    }

    close() {
        this.term._close();
    }

    async processQueue() {
        while (this.msgqueue.length > 0 && this.isConnected) {
            //get first msg
            let data = this.msgqueue.shift();
            let result = await this.push.NotifyClient(this.clientID, data, this.push._pushFunctions.ClientSendSSHExeResult);
            if (!result.sended) {
                this.isConnected = false;
                //emit disconnected
                this.emit('close', this.clientID)

            }
            console.log(result.sended)
        }
        if (this.isConnected) {
            setTimeout(() => {
                this.processQueue()
            }, 20)
        }

    }
};


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

module.exports = SSH;