let path=require('path');
const os = process.platform === 'win32' ? '_win' : '';

let pty = null;//require(ptypath);
const Logger = require('../logs/clsLogger').clsLogger;
const logger = new Logger();
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.msgqueue = [];

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

        pty=require('node-pty')

        let term = pty.spawn(cmder, [], {
            name: 'xterm-color',
            cols: 80,
            rows: 24,
            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();
        this.checkInterval = setInterval(async () => {
            logger.System(`pinging client ${this.clientID}`);
            let result = await this.push.NotifyClient(this.clientID, 'ping', this.push._pushFunctions.Text);
            if (!result.sended){
                this.isConnected = false;
                //emit disconnected
                this.emit('close', this.clientID)
            }
        }, 10000)
    }

    close() {
        clearInterval(this.checkInterval);
        this.isConnected = false;
        this.term._close();
    }

    write(msg) {
        //console.log(msg)
        this.term.write(msg);
    }

    async processQueue() {
        while (this.msgqueue.length > 0 && this.isConnected) {
            //get first msg
            let data = '';
            while (this.msgqueue.length > 0 && data.length < 50) {
                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;
