"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PmacUnsolicitedAutoClient = void 0;
const unsolicited_base_client_1 = require("./unsolicited-base-client");
class PmacUnsolicitedAutoClient extends unsolicited_base_client_1.PmacUnsolicitedBaseClient {
    get connected() {
        return this._connected;
    }
    constructor(sshClient, buffers) {
        super(sshClient, buffers);
        this._running = false;
        this._connected = false;
        sshClient.on('disconnect', () => {
            this._connected = false;
            this.emit('disconnect');
            setTimeout(() => this._tryConnect());
        });
        sshClient.on('error', (err) => {
            this.emit('error', err);
        });
    }
    _tryConnect() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this._running) {
                return;
            }
            try {
                yield this._connect();
                this._connected = true;
                this.emit('connect');
                return;
            }
            catch (err) {
                if (!err.level) {
                    this.emit('error', err);
                }
            }
            setTimeout(() => this._tryConnect(), 1000);
        });
    }
    start() {
        this._running = true;
        this._tryConnect();
    }
    stop() {
        this._running = false;
        this._sshClient.close();
    }
}
exports.PmacUnsolicitedAutoClient = PmacUnsolicitedAutoClient;
