#!/usr/bin/env node
"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 });
var program = require("commander");
var promises_1 = require("fs/promises");
var path = require("path");
var Log_1 = require("./models/Log");
var index_1 = require("./index");
function validateAppTypeJSONInput(input) {
    if (typeof input.state !== 'object') {
        new Log_1.Log(false).error('appType custom shadow is missing object value for "state" key');
        return false;
    }
    if (typeof input.state.reported !== 'object') {
        new Log_1.Log(false).error('appType custom shadow "state" object is missing object value for "reported" key');
        return false;
    }
    return true;
}
var handleAppType = function (input, _) { return __awaiter(void 0, void 0, void 0, function () {
    var file, err_1;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                if (input === 'mss' || input === 'atv2') {
                    return [2 /*return*/, input];
                }
                if (input[0] !== '[' && input[0] !== '{' && !input.includes('.json')) {
                    new Log_1.Log(false).error('Input for appType may only be "mss", "atv2", JSON-encoded object, or path to a json file.');
                    process.exit();
                }
                if (!input.includes('.json')) return [3 /*break*/, 4];
                file = path.join(__dirname, '../' + input);
                _a.label = 1;
            case 1:
                _a.trys.push([1, 3, , 4]);
                return [4 /*yield*/, promises_1.readFile(file, 'utf8')];
            case 2:
                input = _a.sent();
                return [3 /*break*/, 4];
            case 3:
                err_1 = _a.sent();
                new Log_1.Log(false).error("Error opening file: " + err_1);
                process.exit();
                return [3 /*break*/, 4];
            case 4:
                try {
                    input = JSON.parse(input);
                    if (!validateAppTypeJSONInput(input)) {
                        new Log_1.Log(false).info("Expected input: '{\"state\":{\"reported\":{...}, \"desired\":{...}}}', \"desired\" is optional.");
                        process.exit();
                    }
                }
                catch (err) {
                    new Log_1.Log(false).error('Error parsing JSON:' + err.message);
                    process.exit();
                }
                return [2 /*return*/, input];
        }
    });
}); };
var handleJobExecution = function (input, _) {
    var validPath = /^[0-5]$/;
    if (!validPath.test(input)) {
        new Log_1.Log(false).error('Input for jobExecutionPath must be a number between 0 and 5');
        process.exit();
    }
    return input;
};
var getConfig = function (env, args) {
    return program
        .requiredOption('-k, --api-key <apiKey>', 'API key for nRF Cloud', env.API_KEY)
        .option('-c, --certs-response <certsResponse>', 'JSON returned by call to the Device API endpoint: POST /devices/{deviceid}/certificates', env.CERTS_RESPONSE)
        .option('-e, --endpoint <endpoint>', 'AWS IoT MQTT endpoint', env.MQTT_ENDPOINT)
        .option('-d, --device-id <deviceId>', 'ID of the device', env.DEVICE_ID)
        .option('-o, --device-ownership-code <deviceOwnershipCode>', 'PIN/ownership code of the device', env.DEVICE_OWNERSHIP_CODE || '123456')
        .option('-m, --mqtt-messages-prefix <mqttMessagesPrefix>', 'The prefix for the MQTT unique to this tenant for sending and receiving device messages', env.MQTT_MESSAGES_PREFIX)
        .option('-s, --services <services>', 'Comma-delimited list of services to enable. Any of: [gps,acc,temp,device,rsrp,location,log,alert]')
        .option('-f, --app-fw-version <appFwVersion>', 'Version of the app firmware', '1')
        .option('-h, --api-host <apiHost>', 'API host for nRF Cloud', env.API_HOST ? env.API_HOST : 'https://api.nrfcloud.com')
        .option('-a, --associate', 'automatically associate device to account', false)
        .option('-v, --verbose', 'output debug info', false)
        .option('-t, --app-type <appType>', 'Specifies the shadow to use. For custom shadow, pass a JSON-encoded shadow object or relative path to json file. Otherwise, pass "mss" or "atv2" to automatically generate a conformal shadow', handleAppType)
        .option('-p, --job-execution-path <jobExecutionPath>', 'Specifies an unhappy job execution path for a fota update. View the "Use an unhappy path for FOTA execution" section of the README for more details.', handleJobExecution)
        .parse(args)
        .opts();
};
var verbose;
(function () { return __awaiter(void 0, void 0, void 0, function () {
    var config, hostSplit, stage, _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                config = getConfig(process.env, process.argv);
                verbose = !!config.verbose;
                hostSplit = config.apiHost.split('.');
                stage = hostSplit.length === 3 ? 'prod' : hostSplit[1];
                // dev is default stage for sub accounts (ie https://api.coha.nrfcloud.com)
                if (['dev', 'beta', 'prod'].includes(stage) === false) {
                    stage = 'dev';
                }
                config.stage = stage;
                _a = config;
                return [4 /*yield*/, config.appType];
            case 1:
                _a.appType = _b.sent();
                return [2 /*return*/, index_1.run(config)];
        }
    });
}); })().catch(function (err) { return new Log_1.Log(verbose).error(err); });
