"use strict";
var __extends = (this && this.__extends) || (function() {
    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({
                    __proto__: []
                }
                instanceof Array && function(d, b) {
                    d.__proto__ = b;
                }) ||
            function(d, b) {
                for (var p in b)
                    if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
            };
        return extendStatics(d, b);
    };
    return function(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);

        function __() {
            this.constructor = d;
        }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 __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.WebsocketVisitorClient = void 0;
var websocket_client_core_1 = __importDefault(require("@smartsupp/websocket-client-core"));
var websocket_client_utils_1 = require("@smartsupp/websocket-client-utils");
var WebsocketVisitorClient = /** @class */ (function(_super) {
    __extends(WebsocketVisitorClient, _super);

    function WebsocketVisitorClient(options) {
        var _this = _super.call(this, options.connection) || this;
        _this.serverVersion = null;
        _this.updatedValues = {};
        _this.connectData = options.data;
        _this.identity = null; // initialized after first connect to server
        return _this;
    }
    WebsocketVisitorClient.prototype.setConnection = function(connection) {
        _super.prototype.setConnection.call(this, connection);
        connection.on('server.error', (0, websocket_client_utils_1.bound)(this, 'onServerError'));
        connection.on('account.updated', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'account.updated'));
        connection.on('agent.updated', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'agent.updated'));
        connection.on('agent.status_updated', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'agent.status_updated'));
        connection.on('agent.removed', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'agent.removed'));
        connection.on('visitor.updated', (0, websocket_client_utils_1.bound)(this, 'onVisitorUpdated'));
        connection.on('chat.updated', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.updated'));
        connection.on('chat.agent_joined', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.agent_joined'));
        connection.on('chat.agent_assigned', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.agent_assigned'));
        connection.on('chat.agent_unassigned', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.agent_unassigned'));
        connection.on('chat.agent_left', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.agent_left'));
        connection.on('chat.opened', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.opened'));
        connection.on('chat.served', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.served'));
        connection.on('chat.closed', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.closed'));
        connection.on('chat.visitor_closed', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.visitor_closed'));
        connection.on('chat.message_received', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.message_received'));
        connection.on('chat.message_updated', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.message_updated'));
        connection.on('chat.message_deleted', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.message_deleted'));
        connection.on('chat.agent_typing', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.agent_typing'));
        connection.on('chat.rated', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.rated'));
        connection.on('chat.rating_cancelled', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.rating_cancelled'));
        connection.on('chat.rating_suggested', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.rating_suggested'));
        connection.on('chat.contact_read', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.contact_read'));
        connection.on('chat.deleted', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.deleted'));
        connection.on('chat.ticket_form_finish', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.ticket_form_finish'));
        connection.on('chat.transcript_pdf', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'chat.transcript_pdf'));
        connection.on('contact.acquired', (0, websocket_client_utils_1.createEmitter)(this.emitter, 'contact.acquired'));
    };
    WebsocketVisitorClient.prototype.on = function(event, listener) {
        this.emitter.on(event, listener);
        return this;
    };
    WebsocketVisitorClient.prototype.once = function(event, listener) {
        this.emitter.once(event, listener);
        return this;
    };
    WebsocketVisitorClient.prototype.getId = function() {
        return this.identity ? this.identity.id : null;
    };
    WebsocketVisitorClient.prototype.getIdentity = function() {
        return this.identity;
    };
    WebsocketVisitorClient.prototype.connect = function() {
        return _super.prototype.connect.call(this);
    };
    WebsocketVisitorClient.prototype.disconnect = function(logout) {
        if (logout === void 0) {
            logout = false;
        }
        return __awaiter(this, void 0, void 0, function() {
            var _this = this;
            return __generator(this, function(_a) {
                switch (_a.label) {
                    case 0:
                        if (!logout) return [3 /*break*/ , 2];
                        return [4 /*yield*/ , new Promise(function(resolve, reject) {
                            _this.send('visitor.logout', {}, (0, websocket_client_utils_1.createCallback)(resolve, reject));
                        })];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        return [2 /*return*/ , _super.prototype.disconnect.call(this)];
                }
            });
        });
    };
    //
    // API methods
    //
    WebsocketVisitorClient.prototype.update = function(values) {
        if (values === void 0) {
            values = {};
        }
        this.checkServerVersion();
        for (var name_1 in values) {
            this.identity[name_1] = values[name_1];
            this.updatedValues[name_1] = values[name_1];
        }
        this.saveVisitorValues();
    };
    WebsocketVisitorClient.prototype.authenticate = function(values) {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('visitor.authenticate', {
                values: values,
            }, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.notify = function(name, value) {
        var _this = this;
        if (value === void 0) {
            value = null;
        }
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('visitor.notify', {
                name: name,
                value: value,
            }, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatRead = function() {
        this.checkServerVersion();
        this.send('chat.read', null);
    };
    WebsocketVisitorClient.prototype.chatTyping = function(is, text) {
        if (text === void 0) {
            text = null;
        }
        this.checkServerVersion();
        this.send('chat.typing', {
            typing: {
                is: is,
                text: text
            },
        });
    };
    WebsocketVisitorClient.prototype.chatMessage = function(options) {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.message', options, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatClose = function(type) {
        if (type === void 0) {
            type = null;
        }
        this.checkServerVersion();
        this.send('chat.close', {
            type: type,
        });
    };
    WebsocketVisitorClient.prototype.chatUploadInit = function() {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.upload_init', null, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatUploadFinish = function(uploadToken) {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.upload_finish', {
                uploadToken: uploadToken,
            }, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatTranscript = function(email, lang) {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.transcript', {
                email: email,
                lang: lang,
            }, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatTicketFormFinish = function(data) {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.ticket_form_finish', data, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatRateInit = function() {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.rate_init', null, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatRate = function(rating) {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.rate', rating, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.chatTranscriptPdf = function() {
        var _this = this;
        this.checkServerVersion();
        return new Promise(function(resolve, reject) {
            _this.send('chat.transcript_pdf', null, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.visitorConnect = function() {
        var _this = this;
        var values = __assign({
            version: WebsocketVisitorClient.CLIENT_VERSION
        }, this.connectData);
        for (var key in this.updatedValues) {
            values[key] = this.updatedValues[key];
        }
        this.updatedValues = {};
        if (this.identity) {
            for (var key in this.identity) {
                if (!['bannedAt', 'chatId', 'status'].includes(key)) { // filter out read-only props
                    values[key] = this.identity[key];
                }
            }
        }
        this.emitter.emit('initialize', values);
        return new Promise(function(resolve, reject) {
            _this.connection.emit('visitor.connect', values, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    WebsocketVisitorClient.prototype.visitorDisconnect = function() {
        var _this = this;
        return new Promise(function(resolve, reject) {
            _this.connection.emit('visitor.disconnect', {}, (0, websocket_client_utils_1.createCallback)(resolve, reject));
        });
    };
    //
    // Event handlers
    //
    WebsocketVisitorClient.prototype.onVisitorUpdated = function(data) {
        var changes = {};
        for (var name_2 in data.changes) {
            if (WebsocketVisitorClient.identityProperties.includes(name_2)) {
                if (this.identity) {
                    this.identity[name_2] = data.changes[name_2];
                }
                changes[name_2] = data.changes[name_2];
            }
        }
        if (Object.getOwnPropertyNames(changes).length > 0) {
            this.emitter.emit('visitor.updated', changes);
        }
    };
    WebsocketVisitorClient.prototype.onServerError = function(data) {
        var err = (0, websocket_client_utils_1.createSocketError)(data);
        this.emitter.emit('error', err);
    };
    //
    // Utils, data formatting
    //
    WebsocketVisitorClient.prototype.initialize = function() {
        var _this = this;
        return this.visitorConnect().then(function(data) {
            _this.serverVersion = data.serverVersion;
            _this.identity = __assign(__assign({}, data.visitor), {
                variables: __assign({}, data.visitor.variables)
            });
            return data;
        });
    };
    WebsocketVisitorClient.prototype.saveVisitorValues = function() {
        var _this = this;
        if (!this.initialized) {
            return; // update only if initialized
        }
        setTimeout(function() {
            if (!_this.initialized || (Object.getOwnPropertyNames(_this.updatedValues).length === 0)) {
                return;
            }
            var values = {};
            for (var key in _this.updatedValues) {
                values[key] = _this.updatedValues[key];
            }
            _this.send('visitor.update', {
                values: values
            });
            _this.updatedValues = {};
        }, 1);
    };
    WebsocketVisitorClient.prototype.checkServerVersion = function() {
        if (this.serverVersion === null) {
            throw new Error('Client not yet connected to server');
        }
    };
    WebsocketVisitorClient.CLIENT_VERSION = 6;
    WebsocketVisitorClient.identityProperties = [
        'id', 'name', 'email', 'phone', 'chatId', 'variables', 'lang', 'group', 'bannedAt', 'triggerable', 'visits', 'gdprApproved',
    ];
    return WebsocketVisitorClient;
}(websocket_client_core_1.default));
exports.WebsocketVisitorClient = WebsocketVisitorClient;
(function(WebsocketVisitorClient) {
    var EventName;
    (function(EventName) {
        EventName["WidgetOpen"] = "widget_open";
        EventName["WidgetShow"] = "widget_show";
        EventName["VisitorActive"] = "visitor_active";
        EventName["VisitorInactive"] = "visitor_inactive";
    })(EventName = WebsocketVisitorClient.EventName || (WebsocketVisitorClient.EventName = {}));
})(WebsocketVisitorClient = exports.WebsocketVisitorClient || (exports.WebsocketVisitorClient = {}));
exports.WebsocketVisitorClient = WebsocketVisitorClient;
//# sourceMappingURL=data:application/json;base64, 