"use strict";
/// <reference types="socket.io-client" />
var __assign = (this && this.__assign) || function() {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s)
                if (Object.prototype.hasOwnProperty.call(s, p))
                    t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
            enumerable: true,
            get: function() {
                return m[k];
            }
        };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m)
        if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
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());
    });
};
var __generator = (this && this.__generator) || function(thisArg, body) {
    var _ = {
            label: 0,
            sent: function() {
                if (t[0] & 1) throw t[1];
                return t[1];
            },
            trys: [],
            ops: []
        },
        f, y, t, g;
    return g = {
        next: verb(0),
        "throw": verb(1),
        "return": verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g;

    function verb(n) {
        return function(v) {
            return step([n, v]);
        };
    }

    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [0];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [6, e];
            y = 0;
        } finally {
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
};
var __importDefault = (this && this.__importDefault) || function(mod) {
    return (mod && mod.__esModule) ? mod : {
        "default": mod
    };
};
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.SocketError = void 0;
var websocket_client_utils_1 = require("@smartsupp/websocket-client-utils");
var eventemitter3_1 = __importDefault(require("eventemitter3"));
var socket_io_client_1 = __importDefault(require("socket.io-client"));
var helpers_1 = require("./helpers");
var defaultOptions = {
    transports: ['websocket'],
    path: '/socket',
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 5000,
    reconnectionAttempts: Number.POSITIVE_INFINITY,
};
var WebsocketClient = /** @class */ (function() {
    function WebsocketClient(options) {
        this.options = options;
        this.initialized = false;
        this.forceReconnect = false;
        this.identity = null;
        this.connection = null;
        this.connectCallback = null;
        this.disconnectCallback = null;
        this.initData = null;
        this.internalReconnection = false;
        this.internalReconnecting = false;
        this.internalReconnectingAttempt = 0;
        this.emitter = new eventemitter3_1.default();
        this.sendBuffer = [];
        this.options.options = __assign(__assign(__assign({}, defaultOptions), this.options.options), {
            autoConnect: false
        });
    }
    WebsocketClient.prototype.initConnection = function() {
        return __awaiter(this, void 0, void 0, function() {
            var config;
            return __generator(this, function(_a) {
                switch (_a.label) {
                    case 0:
                        if (this.connection) {
                            throw new Error('Connection already exists');
                        }
                        if (!this.options.socket) return [3 /*break*/ , 1];
                        (0, websocket_client_utils_1.debug)("using socket ".concat(this.options.socket.id));
                        this.internalReconnection = false;
                        this.setConnection(this.options.socket);
                        return [3 /*break*/ , 4];
                    case 1:
                        if (!this.options.balancerUrl) return [3 /*break*/ , 3];
                        return [4 /*yield*/ , (0, helpers_1.fetchBalancerConfig)(this.options.balancerUrl)];
                    case 2:
                        config = _a.sent();
                        (0, websocket_client_utils_1.debug)("creating socket to ".concat(config.url, " with token ").concat(config.token));
                        this.internalReconnection = true;
                        this.setConnection((0, socket_io_client_1.default)(config.url, __assign(__assign({}, this.options.options), {
                            autoConnect: false,
                            reconnection: false,
                            query: {
                                token: config.token
                            }
                        })), true);
                        return [3 /*break*/ , 4];
                    case 3:
                        if (this.options.url) {
                            (0, websocket_client_utils_1.debug)("creating socket to ".concat(this.options.url));
                            this.internalReconnection = false;
                            this.setConnection((0, socket_io_client_1.default)(this.options.url, __assign(__assign({}, this.options.options), {
                                autoConnect: false
                            })));
                        } else {
                            throw new Error('Missing required parameter url');
                        }
                        _a.label = 4;
                    case 4:
                        return [2 /*return*/ ];
                }
            });
        });
    };
    WebsocketClient.prototype.setConnection = function(connection, internalReconnection) {
        var _this = this;
        if (internalReconnection === void 0) {
            internalReconnection = false;
        }
        this.connection = connection;
        this.forceReconnect = false;
        this.internalReconnection = internalReconnection;
        connection.on('connect_error', function(err) {
            if (_this.internalReconnection) {
                _this.connectCallback = null;
                (0, websocket_client_utils_1.debug)('connection was not reconnected');
                _this.emitter.emit('reconnect_error', err);
                if (_this.options.options.reconnectionAttempts > _this.internalReconnectingAttempt + 1) {
                    void _this.reconnect(_this.internalReconnectingAttempt + 1);
                } else {
                    _this.emitter.emit('reconnect_failed', _this.internalReconnectingAttempt);
                }
            }
        });
        connection.on('connect', function() {
            (0, websocket_client_utils_1.debug)('socket was connected');
            _this.initialized = false;
            if (!_this.internalReconnecting) {
                _this.emitter.emit('connect');
            } else {
                (0, websocket_client_utils_1.debug)('connection is reconnected');
                _this.emitter.emit('reconnect');
                _this.internalReconnecting = false;
                _this.internalReconnectingAttempt = 0;
            }
            void _this.initialize().then(function(data) {
                (0, websocket_client_utils_1.debug)('socket was initialized');
                _this.onInitialized(data);
                if (_this.connectCallback) {
                    _this.connectCallback(null, data);
                    _this.connectCallback = null;
                }
                return data;
            }).catch(function(err) {
                (0, websocket_client_utils_1.debug)('socket was not initialized ', __assign({}, err));
                _this.onInitializeError(err);
                if (_this.connectCallback) {
                    _this.connectCallback(err);
                    _this.connectCallback = null;
                }
            });
        });
        connection.on('disconnect', function(reason) {
            (0, websocket_client_utils_1.debug)("socket was disconnected reason='".concat(reason, "'"));
            _this.initialized = false;
            // in case of internal reconnection emit disconnect only once
            if (!_this.internalReconnecting || _this.internalReconnectingAttempt === 1) {
                // connection is properly disconnected after some time
                setTimeout(function() {
                    _this.emitter.emit('disconnect', reason);
                    if (_this.disconnectCallback) {
                        _this.disconnectCallback();
                        _this.disconnectCallback = null;
                    }
                }, 100);
            }
            // should start internal reconnecting?
            if (_this.options.options.reconnection &&
                _this.internalReconnection &&
                !_this.internalReconnecting &&
                (_this.forceReconnect || reason !== 'io server disconnect')) {
                void _this.reconnect();
            }
        });
        connection.on('reconnecting', function(attempt) {
            _this.emitter.emit('reconnecting', attempt);
        });
        connection.on('reconnect', function() {
            _this.emitter.emit('reconnect');
        });
        connection.on('reconnect_attempt', function(attempt) {
            _this.emitter.emit('reconnect_attempt', attempt);
        });
        connection.on('reconnect_error', function(err) {
            _this.emitter.emit('reconnect_error', err);
        });
        connection.on('reconnect_failed', function() {
            _this.emitter.emit('reconnect_failed');
        });
        connection.on('force_reconnect', function() {
            (0, websocket_client_utils_1.debug)('received event force_reconnect, setting flag forceReconnect = true');
            _this.forceReconnect = true;
        });
    };
    WebsocketClient.prototype.getConnection = function() {
        return this.connection;
    };
    WebsocketClient.prototype.isConnected = function() {
        var _a;
        return ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.connected) || false;
    };
    WebsocketClient.prototype.isInitialized = function() {
        return this.initialized;
    };
    WebsocketClient.prototype.getInitData = function() {
        return this.initData;
    };
    WebsocketClient.prototype.connect = function() {
        return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.connection) return [3 /*break*/ , 2];
                        return [4 /*yield*/ , this.initConnection()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        return [2 /*return*/ , new Promise(function(resolve, reject) {
                            if (_this.initialized) {
                                resolve(_this.initData);
                            } else {
                                (0, websocket_client_utils_1.debug)('starting connecting');
                                _this.connectCallback = (0, websocket_client_utils_1.createCallback)(resolve, reject);
                                _this.connection.open();
                            }
                        })];
                }
            });
        });
    };
    WebsocketClient.prototype.disconnect = function() {
        var _this = this;
        return new Promise(function(resolve, reject) {
            if (!_this.connection || _this.connection.disconnected) {
                _this.connection = null;
                resolve();
            } else {
                (0, websocket_client_utils_1.debug)('starting disconnecting');
                _this.disconnectCallback = (0, websocket_client_utils_1.createCallback)(resolve, reject);
                _this.connection.close();
                _this.connection = null;
            }
        });
    };
    WebsocketClient.prototype.reconnect = function(attepmt) {
        var _this = this;
        if (attepmt === void 0) {
            attepmt = 1;
        }
        this.internalReconnecting = true;
        this.internalReconnectingAttempt = attepmt;
        return this.disconnect().then(function() {
            // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
            var delay = Math.floor(Math.random() * (_this.options.options.reconnectionDelayMax - _this.options.options.reconnectionDelay) + _this.options.options.reconnectionDelay);
            (0, websocket_client_utils_1.debug)("connection will reconnect in ".concat(delay, "ms"));
            _this.emitter.emit('reconnecting', attepmt);
            return new Promise(function(resolve) {
                setTimeout(resolve, delay);
            });
        }).then(function() {
            (0, websocket_client_utils_1.debug)('connection is starting reconnect');
            _this.emitter.emit('reconnect_attempt', attepmt);
            return _this.connect();
        });
    };
    WebsocketClient.prototype.initialize = function() {
        return new Promise(function(resolve) {
            resolve({});
        });
    };
    WebsocketClient.prototype.onInitialized = function(data) {
        var _this = this;
        if (this.initialized)
            return;
        this.initialized = true;
        this.initData = data;
        (0, websocket_client_utils_1.debug)('emit initialized');
        this.emitter.emit('initialized', data);
        setTimeout(function() {
            if (_this.sendBuffer.length > 0) {
                (0, websocket_client_utils_1.debug)("sending buffered ".concat(_this.sendBuffer.length, " events"));
                for (var i = 0; i < _this.sendBuffer.length; i++) {
                    var packet = _this.sendBuffer[i];
                    _this.connection.emit(packet.name, packet.data, packet.callback);
                }
                _this.sendBuffer = [];
            }
        }, 1);
    };
    WebsocketClient.prototype.onInitializeError = function(err) {
        void this.disconnect(); // in this case reconnect is not possible
        (0, websocket_client_utils_1.debug)('emit initialize_error', __assign({}, err));
        this.emitter.emit('initialize_error', err);
    };
    WebsocketClient.prototype.send = function(name, data, callback) {
        if (this.initialized) {
            this.connection.emit(name, data, callback);
        } else {
            this.sendBuffer.push({
                name: name,
                data: data,
                callback: callback
            });
        }
    };
    WebsocketClient.prototype.on = function(event, listener) {
        this.emitter.on(event, listener);
        return this;
    };
    WebsocketClient.prototype.once = function(event, listener) {
        this.emitter.once(event, listener);
        return this;
    };
    WebsocketClient.prototype.removeAllListeners = function() {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        (_a = this.emitter).removeAllListeners.apply(_a, args);
        return this;
    };
    return WebsocketClient;
}());
exports.default = WebsocketClient;
var websocket_client_utils_2 = require("@smartsupp/websocket-client-utils");
Object.defineProperty(exports, "SocketError", {
    enumerable: true,
    get: function() {
        return websocket_client_utils_2.SocketError;
    }
});
__exportStar(require("./mock"), exports);
//# sourceMappingURL=data:application/json;base64, 