"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());
    });
};
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 });
exports.nrfdevice = void 0;
var mqttClient_1 = require("./mqttClient");
var Device_1 = require("./models/Device");
var Job_1 = require("./models/Job");
var Log_1 = require("./models/Log");
exports.nrfdevice = function (config, sensors, apiConn, onConnect, log) {
    if (log === void 0) { log = new Log_1.Log(true); }
    var deviceId = config.deviceId, caCert = config.caCert, clientCert = config.clientCert, privateKey = config.privateKey, endpoint = config.endpoint, appFwVersion = config.appFwVersion, mqttMessagesPrefix = config.mqttMessagesPrefix, stage = config.stage, tenantId = config.tenantId;
    var shadowInitted = false;
    var onConnectExecuted = false;
    var onConnectExecuting = false;
    log.success("connecting to \"" + endpoint + "\"...");
    var client = mqttClient_1.mqttClient({
        id: deviceId,
        caCert: caCert,
        clientCert: clientCert,
        privateKey: privateKey,
        endpoint: endpoint,
    });
    var device = new Device_1.NrfDevice(deviceId, mqttMessagesPrefix, stage, tenantId, client, sensors, log);
    var jobsManager = new Job_1.NrfJobsManager(device, log);
    var notifyOfConnection = function (eventName) { return __awaiter(void 0, void 0, void 0, function () {
        var deviceAssociated_1, didHaveError_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!shadowInitted) return [3 /*break*/, 2];
                    shadowInitted = true;
                    log.info("Initializing " + deviceId + " shadow...");
                    return [4 /*yield*/, device.initShadow(appFwVersion)];
                case 1:
                    _a.sent();
                    _a.label = 2;
                case 2:
                    if (!(onConnect && !onConnectExecuted && !onConnectExecuting)) return [3 /*break*/, 5];
                    onConnectExecuting = true;
                    log.debug("TRIGGERING ONCONNECT CALLBACK ON \"" + eventName + "\"");
                    return [4 /*yield*/, onConnect(deviceId)];
                case 3:
                    _a.sent();
                    // wait for a couple seconds
                    return [4 /*yield*/, new Promise(function (resolve) {
                            var halfSecondsElapsed = 1;
                            var totalDelay = 10; // 10 half seconds
                            log.info('waiting for aws IoT to associate device...');
                            var intervalId = setInterval(function () {
                                log.debug('.'.repeat(totalDelay - halfSecondsElapsed));
                                halfSecondsElapsed++;
                                if (halfSecondsElapsed >= totalDelay) {
                                    clearInterval(intervalId);
                                    resolve();
                                }
                            }, 500);
                        })];
                case 4:
                    // wait for a couple seconds
                    _a.sent();
                    onConnectExecuted = true;
                    _a.label = 5;
                case 5:
                    if (!(!onConnect || onConnectExecuted)) return [3 /*break*/, 7];
                    deviceAssociated_1 = false;
                    didHaveError_1 = false;
                    // listen for jobs, if associated
                    log.debug("checking to see if device " + deviceId + " has been associated...");
                    return [4 /*yield*/, apiConn
                            .get("v1/devices/" + deviceId)
                            .then(function (res) { return __awaiter(void 0, void 0, void 0, function () {
                            var _a;
                            return __generator(this, function (_b) {
                                switch (_b.label) {
                                    case 0:
                                        if (!(((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.tenantId) === tenantId)) return [3 /*break*/, 2];
                                        log.success("confirmed that \"" + deviceId + "\" has been associated with account \"" + tenantId + "\"!");
                                        deviceAssociated_1 = true;
                                        log.info('listening for new jobs...');
                                        return [4 /*yield*/, jobsManager.waitForJobs()];
                                    case 1:
                                        _b.sent();
                                        _b.label = 2;
                                    case 2: return [2 /*return*/];
                                }
                            });
                        }); })
                            .catch(function (err) {
                            var _a, _b, _c;
                            var code = (_b = (_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.code;
                            if (code !== 40410) {
                                log.error("Error getting data for device \"" + deviceId + "\". Cannot initialize jobs listener. Error: \"" + (((_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data) ? JSON.stringify(err.response.data, null, 2)
                                    : err) + "\"");
                                didHaveError_1 = true;
                            }
                        })
                            .finally(function () {
                            if (!deviceAssociated_1 && !didHaveError_1) {
                                log.info("Cannot initialize jobs listener until the device \"" + deviceId + "\" is associated to your account. You can associate the device by running \"npx @nrfcloud/device-simulator-v2 -k <api key> -d " + deviceId + " -a\".");
                            }
                        })];
                case 6:
                    _a.sent();
                    _a.label = 7;
                case 7: return [2 /*return*/];
            }
        });
    }); };
    client.on('error', function (error) {
        log.error("AWS IoT error " + error.message);
    });
    client.on('connect', function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    log.success('connected');
                    return [4 /*yield*/, notifyOfConnection('connect')];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
    client.on('message', function (topic, payload) {
        log.incoming(topic, payload || {});
        var p = payload ? JSON.parse(payload.toString()) : {};
        if (device.listeners[topic]) {
            device.listeners[topic]({
                topic: topic,
                payload: p,
            });
        }
        else {
            throw new Error("No listener registered for topic " + topic + "!");
        }
    });
    client.on('close', function () {
        log.error('disconnect');
    });
    client.on('reconnect', function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    log.success('reconnect');
                    return [4 /*yield*/, notifyOfConnection('reconnect')];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
    return {
        publish: device.publish,
        subscribe: device.subscribe,
        registerListener: device.registerListener,
        unregisterListener: device.unregisterListener,
        run: function () { return __awaiter(void 0, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, jobsManager.waitForJobs().catch(function (e) { return log.error(e); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); },
    };
};
