"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 (_) 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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var response_error_1 = require("../client/api/response/response-error");
var target_variable_1 = require("./target-variable");
var aes_ecb_128_converter_1 = require("../core/crypto/aes-ecb-128-converter");
var scram_1 = require("./scram");
var format_helper_1 = require("../core/format/format-helper");
var iotize_device_services_1 = require("./iotize-device-services");
var bundle_manager_1 = require("./target-variable/bundle-manager");
var service_1 = require("./service");
var api_1 = require("../client/api");
var api_config_factory_1 = require("./config/api-config-factory");
var crc_1 = require("../core/error-detection/crc");
var crypto_helper_1 = require("./config/crypto-helper");
var converter_1 = require("./converter");
require("../core/extensions");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
require("../client/impl/frame/stream-generated");
var default_iotize_client_1 = require("../client/impl/default-iotize-client");
var Tap;
(function (Tap) {
    function create() {
        return new IoTizeDevice(default_iotize_client_1.DefaultIoTizeClient.create());
    }
    Tap.create = create;
    function fromProtocol(protocol) {
        var client = default_iotize_client_1.DefaultIoTizeClient.create();
        client.addComProtocol(protocol);
        return new IoTizeDevice(client);
    }
    Tap.fromProtocol = fromProtocol;
})(Tap = exports.Tap || (exports.Tap = {}));
/**
 *
 * @deprecated Use Tap instead
 */
var IoTizeDevice = /** @class */ (function () {
    function IoTizeDevice(client) {
        this._client = client;
        this._initCache();
        this._apiConfig = api_config_factory_1.ApiConfigFactory.getDefaultInstance();
        // this._converterProvider = new ConverterProvider(PathToTypeMap, DefaultConverterMap);
        this._services = iotize_device_services_1.IoTizeDeviceService.create(this._client, this._apiConfig);
        if (!this.client.getEncryptionAlgo()) {
            this.client.setEncryptionAlgo(new aes_ecb_128_converter_1.AesEcb128Converter());
        }
        this._lwm2m = new Lwm2mInterface(this.client, this._apiConfig);
    }
    Object.defineProperty(IoTizeDevice.prototype, "lockOptions", {
        get: function () {
            if (!this._interfaceLockOptions) {
                this._interfaceLockOptions = {
                    factoryReset: false,
                    resourceFactory: false,
                    hashPassword: false,
                    resourceLogUid: false,
                    scramActivated: false
                };
            }
            return this._interfaceLockOptions;
        },
        set: function (value) {
            this._interfaceLockOptions = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "sessionKey", {
        get: function () {
            return this._sessionKey;
        },
        /**
         * Setter for the session key
         * @param key if null, it will stop encryption and remove session key. If true it will update session key used for encryption
         */
        set: function (key) {
            this._sessionKey = key;
            if (this._sessionKey) {
                var options = {
                    key: format_helper_1.FormatHelper.toHexString(this._sessionKey),
                    iv: "00000000000000000000000000000000"
                };
                var algo = new aes_ecb_128_converter_1.AesEcb128Converter(options);
                this.client.setEncryptionAlgo(algo);
            }
            else {
                this.client.enableEncryption(false);
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "client", {
        get: function () {
            return this._client;
        },
        set: function (client) {
            this._client = client;
            this._services.client = client;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "sessionState", {
        /**
         * Listen to session state changed
         */
        get: function () {
            // if (!this.isConnected()){
            //     throw new C
            // }
            return this._sessionState$;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @deprecated
     */
    IoTizeDevice.create = function () {
        return Tap.create();
    };
    /**
     * @deprecated
     * @param protocol
     */
    IoTizeDevice.fromProtocol = function (protocol) {
        return Tap.fromProtocol(protocol);
    };
    IoTizeDevice.prototype.encryption = function (enable, resetSessionKey) {
        if (resetSessionKey === void 0) { resetSessionKey = false; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.enableEncryption(enable, resetSessionKey)];
            });
        });
    };
    /**
     * Enable/Disable encrytion when communicating with a device
     * @param enable true if requests must be encrypted
     * @param resetSessionKey true if you want to reset the the session key.
     *
     * @deprecated use {@link encryption()} instead
     */
    IoTizeDevice.prototype.enableEncryption = function (enable, resetSessionKey) {
        if (resetSessionKey === void 0) { resetSessionKey = false; }
        return __awaiter(this, void 0, void 0, function () {
            var response, newSessionKey;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (resetSessionKey) {
                            this._sessionKey = undefined;
                        }
                        if (!(enable && !this._sessionKey)) return [3 /*break*/, 2];
                        console.warn('IoTizeDevice', "No session key defined. Using random com start");
                        return [4 /*yield*/, this.service.scram.initialize()];
                    case 1:
                        response = _a.sent();
                        if (!response.isSuccess()) {
                            return [2 /*return*/, Promise.reject(new Error("Cannot start encrypted session. Scram initialization failed (" + new response_error_1.ResponseError(response).message + ")"))];
                        }
                        newSessionKey = response.rawBody();
                        this.sessionKey = newSessionKey;
                        console.debug('IoTizeDevice', "Session key will be " + format_helper_1.FormatHelper.toHexString(newSessionKey) + " (length=" + newSessionKey.length + ")");
                        _a.label = 2;
                    case 2: return [2 /*return*/, this.client.enableEncryption(enable)];
                }
            });
        });
    };
    Object.defineProperty(IoTizeDevice.prototype, "protocol", {
        get: function () {
            return this.client.getCurrentProtocol();
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Connect with the given communication protocol
     * TODO what if there is already a connected communication protocol
     * @param protocol
     */
    IoTizeDevice.prototype.connect = function (protocol) {
        // this._clearCache();
        if (protocol) {
            this.client.addComProtocol(protocol, "default");
        }
        return this._client.connect().toPromise();
    };
    /**
     * Disconnect device
     * It will also clear session key
     */
    IoTizeDevice.prototype.disconnect = function () {
        this._initCache();
        return this._client.disconnect().toPromise();
    };
    IoTizeDevice.prototype.isConnected = function () {
        if (!this._client) {
            return false;
        }
        return this._client.isConnected();
    };
    Object.defineProperty(IoTizeDevice.prototype, "variables", {
        get: function () {
            if (!this._variableManager) {
                this._variableManager = new target_variable_1.VariableManager(this);
            }
            return this._variableManager;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "bundles", {
        get: function () {
            if (!this._bundleManager) {
                this._bundleManager = new bundle_manager_1.BundleManager(this.service.bundle, this.variables);
            }
            return this._bundleManager;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Setter for hashPassword option
     * @deprecated this should not be used anymore as this configuration must be read from the tap
     */
    // public set hashPassword(enabled: boolean) {
    //     if (!this.interfaceLockOptions) {
    //         this.interfaceLockOptions = {
    //             factoryReset: false,
    //             hashPassword: enabled,
    //             resourceFactory: false,
    //             resourceLogUid: false,
    //             scramActivated: false
    //         }
    //     }
    //     this.interfaceLockOptions.hashPassword = enabled;
    // }
    /**
     * Return true if password will be hashed
     * @deprecated
     */
    // public get hashPassword() {
    //     if (!this.interfaceLockOptions) {
    //         return false;
    //     }
    //     return this.interfaceLockOptions.hashPassword;
    // }
    /**
     * Tap logout
     * Reject if logout failed
     */
    IoTizeDevice.prototype.logout = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._interfaceLockOptions = undefined;
                        this.encryption(false);
                        return [4 /*yield*/, this.service.interface.logout()];
                    case 1:
                        response = _a.sent();
                        response.successful();
                        return [4 /*yield*/, this.refreshSessionState()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Change password for the groupId (If groupId is not specified, it will be changed for the current group id)
     * @param newPassword the new password
     * @param groupId default to the current group id
     */
    IoTizeDevice.prototype.changePassword = function (newPassword, groupId) {
        return __awaiter(this, void 0, void 0, function () {
            var lockInfo, passwordBytes;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(groupId == undefined)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.service.interface.getCurrentGroupId()];
                    case 1:
                        groupId = (_a.sent()).body();
                        _a.label = 2;
                    case 2: return [4 /*yield*/, this.getLockInfo()];
                    case 3:
                        lockInfo = _a.sent();
                        if (lockInfo.hashPassword) {
                            passwordBytes = format_helper_1.FormatHelper.hexStringToBuffer(crypto_helper_1.CryptoHelper.passwordHasher.hash(newPassword));
                            return [2 /*return*/, this.service.group.changePasswordKey(groupId, passwordBytes)];
                        }
                        else {
                            return [2 /*return*/, this.service.group.changePassword(groupId, newPassword)];
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     *
     * @warning this is an experimental function. It may be modified in future releases
     * @experimental
     */
    IoTizeDevice.prototype.loadSinglePacketInStore = function (packets) {
        var _this = this;
        return rxjs_1.Observable.create(function (observer) { return __awaiter(_this, void 0, void 0, function () {
            var index, packet, result, err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 5, , 6]);
                        index = 0;
                        _a.label = 1;
                    case 1:
                        if (!(index < packets.length)) return [3 /*break*/, 4];
                        packet = packets[index];
                        console.debug("sendSinglePacket", "sending packet " + (index + 1) + "/" + packets.length, packet);
                        return [4 /*yield*/, this.service.singlePacket.writePartialSinglePacket(packet)];
                    case 2:
                        result = _a.sent();
                        result.successful();
                        observer.next({
                            total: packets.length,
                            current: index + 1,
                            done: false
                        });
                        console.debug("sendSinglePacket", "Packet " + (index + 1) + "/" + packets.length + " SENT!");
                        _a.label = 3;
                    case 3:
                        index++;
                        return [3 /*break*/, 1];
                    case 4:
                        observer.next({
                            done: true,
                            total: packets.length,
                            current: packets.length,
                        });
                        observer.complete();
                        return [3 /*break*/, 6];
                    case 5:
                        err_1 = _a.sent();
                        // console.error(`ERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR`, err)
                        observer.error(err_1);
                        return [3 /*break*/, 6];
                    case 6: return [2 /*return*/];
                }
            });
        }); });
    };
    /**
     * Send a single packet to the tap and execute
     *
     * @warning this is an experimental function. It may be modified in future releases
     * @experimental
     */
    IoTizeDevice.prototype.sendSinglePacket = function (packetOrModel) {
        var _this = this;
        try {
            var packet_1;
            if (!(packetOrModel instanceof Uint8Array)) {
                var converter = new converter_1.SinglePacketConverter();
                packetOrModel = api_1.SinglePacket.fillComputedField(packetOrModel);
                packet_1 = converter.encode(packetOrModel);
            }
            else {
                packet_1 = packetOrModel;
            }
            if (packet_1.length > api_1.SinglePacket.MAX_PART_SIZE) {
                var packetBuilder = new api_1.SinglePacket.Splitter(api_1.SinglePacket.MAX_PART_SIZE);
                var packets_1 = packetBuilder.chunk(packet_1);
                return this.loadSinglePacketInStore(packets_1)
                    .pipe(operators_1.concat(rxjs_1.Observable.create(function (observer) { return __awaiter(_this, void 0, void 0, function () {
                    var expectedCrc, err_2;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                expectedCrc = crc_1.CRC.fromBytes(packet_1);
                                return [4 /*yield*/, this.service.singlePacket.bspe(expectedCrc)];
                            case 1:
                                (_a.sent()).successful();
                                observer.next({
                                    total: packets_1.length,
                                    current: packets_1.length,
                                    done: true,
                                    crc: expectedCrc
                                });
                                observer.complete();
                                return [3 /*break*/, 3];
                            case 2:
                                err_2 = _a.sent();
                                observer.error(err_2);
                                return [3 /*break*/, 3];
                            case 3: return [2 /*return*/];
                        }
                    });
                }); })));
            }
            else {
                return rxjs_1.Observable.create(function (observer) { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, this.service.singlePacket.writeSmallSinglePacket(packet_1)];
                            case 1:
                                (_a.sent()).successful();
                                observer.next({
                                    total: 1,
                                    current: 1,
                                    done: true
                                });
                                observer.complete();
                                return [2 /*return*/];
                        }
                    });
                }); });
            }
        }
        catch (error) {
            return rxjs_1.throwError(error);
        }
    };
    /**
     * Configure current tap instance thanks to a TapConfigurator
     * @param configurator
     */
    IoTizeDevice.prototype.configure = function (configurator) {
        return configurator.configure(this).toPromise();
    };
    /**
     * Tap login
     *
     */
    IoTizeDevice.prototype.login = function (username, password, refreshSessionState) {
        if (refreshSessionState === void 0) { refreshSessionState = true; }
        return __awaiter(this, void 0, void 0, function () {
            var lockInfos, auth, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._log("Login with username " + username + "...");
                        return [4 /*yield*/, this.getLockInfo()];
                    case 1:
                        lockInfos = _a.sent();
                        this._log("Lock infos:", lockInfos);
                        if (!lockInfos.scramActivated) return [3 /*break*/, 4];
                        console.debug('IoTizeDevice', "Using scram login");
                        auth = this.scramAuth;
                        return [4 /*yield*/, auth.login({
                                username: username,
                                password: password
                            })];
                    case 2:
                        _a.sent();
                        console.debug('IoTizeDevice', "Scram login successful!");
                        this.sessionKey = auth.getSessionKey();
                        return [4 /*yield*/, this.enableEncryption(true)];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 9];
                    case 4:
                        response = void 0;
                        if (!lockInfos.hashPassword) return [3 /*break*/, 6];
                        console.debug("Using hash password login");
                        return [4 /*yield*/, this.service.interface.loginWithHash({
                                username: username,
                                password: format_helper_1.FormatHelper.hexStringToBuffer(crypto_helper_1.CryptoHelper.passwordHasher.hash(password))
                            })];
                    case 5:
                        response = _a.sent();
                        return [3 /*break*/, 8];
                    case 6:
                        console.debug("Using regular login");
                        return [4 /*yield*/, this.service.interface.login({
                                username: username,
                                password: password
                            })];
                    case 7:
                        response = _a.sent();
                        _a.label = 8;
                    case 8:
                        response.successful();
                        _a.label = 9;
                    case 9:
                        if (!this._sessionState) {
                            this._sessionState = IoTizeDevice.INITIAL_SESSION_STATE;
                        }
                        this._sessionState.startTime = new Date();
                        if (!refreshSessionState) return [3 /*break*/, 11];
                        return [4 /*yield*/, this.refreshSessionState()];
                    case 10:
                        _a.sent();
                        _a.label = 11;
                    case 11: return [2 /*return*/, true];
                }
            });
        });
    };
    Object.defineProperty(IoTizeDevice.prototype, "scramAuth", {
        get: function () {
            if (!this._scramAuth) {
                this._scramAuth = new scram_1.ScramAuth(this);
            }
            return this._scramAuth;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "rooter", {
        get: function () {
            return this._apiConfig.routes;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "apiConfig", {
        get: function () {
            return this._apiConfig;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "service", {
        get: function () {
            return this._services;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IoTizeDevice.prototype, "lwm2m", {
        /**
         * @experimental
         */
        get: function () {
            return this._lwm2m;
        },
        enumerable: true,
        configurable: true
    });
    // /**
    //  * @deprecated use lwm2m object instead ? 
    //  */
    // public lwm2mCall(...calls: ServiceCallType[]) {
    //     if (calls.length > 1) {
    //         throw new Error("Multiple calls are not implemented yet");
    //     }
    //     let args = AbstractService.callToCommandArgs(calls[0], this.apiConfig);
    //     var response = this.client.command<string>(args[0], args[1]).toPromise();
    //     return response;
    // }
    /**
     * Initialize device cache
     */
    IoTizeDevice.prototype._initCache = function () {
        if (this._sessionState$) {
            this._sessionState$.complete();
        }
        this._interfaceLockOptions = undefined;
        this._sessionState = IoTizeDevice.INITIAL_SESSION_STATE;
        this._sessionState$ = new rxjs_1.BehaviorSubject(this._sessionState || IoTizeDevice.INITIAL_SESSION_STATE);
        this.sessionKey = undefined;
        // this._sessionState$.next(newState)
    };
    /**
     * Read session state from the device
     * This will perform a few tap requests
     */
    IoTizeDevice.prototype.refreshSessionState = function () {
        return __awaiter(this, void 0, void 0, function () {
            var groupId, _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!this._sessionState) {
                            this._sessionState = IoTizeDevice.INITIAL_SESSION_STATE;
                        }
                        console.debug('[TAP]', "Refreshing session state (current=" + this._sessionState.name + ")...");
                        return [4 /*yield*/, this.service.interface.getCurrentGroupId()];
                    case 1:
                        groupId = (_c.sent()).body();
                        if (!(groupId != this._sessionState.groupId)) return [3 /*break*/, 4];
                        this._sessionState.groupId = groupId;
                        _a = this._sessionState;
                        return [4 /*yield*/, this.service.group.getName(groupId)];
                    case 2:
                        _a.name = (_c.sent()).body();
                        _b = this._sessionState;
                        return [4 /*yield*/, this.service.group.getSessionLifetime(groupId)];
                    case 3:
                        _b.lifeTime = (_c.sent()).body();
                        console.debug('[TAP]', "Notifying new session state: " + this._sessionState.name);
                        this._sessionState$.next(this._sessionState);
                        return [3 /*break*/, 5];
                    case 4:
                        console.debug('[TAP]', "Session state did not changed: " + this._sessionState.name + " (id=" + groupId + ")");
                        _c.label = 5;
                    case 5: return [2 /*return*/, this._sessionState];
                }
            });
        });
    };
    /**
     * Get lock info
     */
    IoTizeDevice.prototype.getLockInfo = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this._interfaceLockOptions) return [3 /*break*/, 2];
                        this._log("Reading interface lock options from device...");
                        return [4 /*yield*/, this.service.interface.getLock()];
                    case 1:
                        response = _a.sent();
                        this._interfaceLockOptions = response.body();
                        _a.label = 2;
                    case 2: return [2 /*return*/, this._interfaceLockOptions];
                }
            });
        });
    };
    IoTizeDevice.prototype._log = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        console.debug.apply(console, ['IoTizeDevice'].concat(args));
    };
    IoTizeDevice.TAG = "Tap";
    IoTizeDevice.INITIAL_SESSION_STATE = {
        groupId: 0,
        lifeTime: -1,
        name: "anonymous",
        startTime: undefined
    };
    return IoTizeDevice;
}());
exports.IoTizeDevice = IoTizeDevice;
var Lwm2mInterface = /** @class */ (function () {
    function Lwm2mInterface(client, apiConfig) {
        this.client = client;
        this.apiConfig = apiConfig;
    }
    Lwm2mInterface.prototype.get = function (path, body) {
        return this.call({
            path: path,
            methodType: 'get',
            body: body
        });
    };
    Lwm2mInterface.prototype.put = function (path, body) {
        return this.call({
            path: path,
            methodType: 'put',
            body: body
        });
    };
    Lwm2mInterface.prototype.post = function (path, body) {
        return this.call({
            path: path,
            methodType: 'post',
            body: body
        });
    };
    Lwm2mInterface.prototype.call = function () {
        var calls = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            calls[_i] = arguments[_i];
        }
        var args = service_1.AbstractService.callToCommandArgs(calls[0], this.apiConfig);
        var response = this.client.command(args[0], args[1]).toPromise();
        return response;
    };
    return Lwm2mInterface;
}());
exports.Lwm2mInterface = Lwm2mInterface;
