"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const body_parser_1 = __importDefault(require("body-parser"));
const path_1 = __importDefault(require("path"));
const jon_1 = require("./jon");
const utils_1 = require("./utils");
const provision_1 = require("./provision");
const PORT = 3030;
const app = (0, express_1.default)();
let _provisioningLock = provision_1.ProvisioningStatus.None;
let _prov = null;
let _pollTimer;
app.use(body_parser_1.default.json());
app.use(body_parser_1.default.urlencoded({ extended: true }));
app.use('/assets', express_1.default.static(path_1.default.join(__dirname, 'assets')));
app.get("/", (req, res) => {
    res.send(`<img src='./assets/nothere.jpg'></img>`);
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
app.get("/fbset", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    // make sure to set the correct timings
    yield utils_1.Utils.execHostCommand("fbset -t 39721 48 16 33 10 96 2");
    res.send({
        message: "Done"
    });
}));
app.get("/status", (req, res) => {
    res.send({
        message: _provisioningLock
    });
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
app.post("/provision", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        _provisioningLock = provision_1.ProvisioningStatus.Requested;
        console.log("Loging ...");
        yield jon_1.Jon.Login(req.body.login, req.body.password);
        console.log("Getting Provisioning Token ...");
        const provToken = yield jon_1.Jon.ProvisionToken();
        yield utils_1.Utils.execHostCommand(jon_1.Jon.ProvisionDeviceCommand(provToken));
        _provisioningLock = provision_1.ProvisioningStatus.Done;
        res.send({
            message: "Done"
        });
    }
    catch (e) {
        console.log(e);
        res.send({
            message: `Error :: ${e.code} :: ${e.message}`
        });
    }
}));
// eslint-disable-next-line @typescript-eslint/no-misused-promises
app.get("/code", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        if (_prov === null) {
            _prov = yield provision_1.Provision.GetProvisionCode();
        }
        res.send(_prov);
    }
    catch (e) {
        console.log(e);
        res.send({
            message: `Error :: ${e.code} :: ${e.message}`
        });
    }
}));
app.get("/name", (req, res) => {
    if (_provisioningLock === "done") {
        res.send({
            name: provision_1.Provision.GetPlatformDeviceName()
        });
    }
    else {
        res.send({
            message: "Error :: Device not provisioned"
        });
    }
});
app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
    // if only the server is up we get the code anyway
    void provision_1.Provision.GetProvisionCode();
    // for each 20min refresh the code
    setInterval(() => {
        if (_provisioningLock === "none") {
            console.log("Getting new code ...");
            void provision_1.Provision.GetProvisionCode().then((obj) => {
                _prov = obj;
            });
        }
        else {
            console.log("Device provisioned...");
        }
    }, 1200000);
    // for each 5s check if the code was claimed
    _pollTimer = setInterval(() => {
        if (_provisioningLock !== "done") {
            console.log("Checking if the device was claimed ...");
            try {
                void provision_1.Provision.CheckCodeClaimed(_prov.uuid).then((token) => {
                    _provisioningLock = provision_1.ProvisioningStatus.Requested;
                    clearInterval(_pollTimer);
                    console.log("Device claimed");
                    void utils_1.Utils.execHostCommand(jon_1.Jon.ConfigurePollingFrequencyTo30Secs()).then(() => {
                        console.log("Polling frequency set to 30s");
                        void utils_1.Utils.execHostCommand(jon_1.Jon.ProvisionDeviceCommand(token)).then(() => {
                            console.log("Device provisioned");
                            _provisioningLock = provision_1.ProvisioningStatus.Done;
                            // clean /etc/issue
                            if (!utils_1.Utils.suppressOutputSet) {
                                void utils_1.Utils.execHostCommand(
                                // eslint-disable-next-line max-len
                                `echo -e '\nThis device was successfully paired on Torizon Cloud!\n The name of this device is: ${provision_1.Provision.GetPlatformDeviceName()}\nVisit https://app.pilot.torizon.io/#/packages to deploy samples!\n' > /etc/issue`);
                            }
                        }).catch((e) => {
                            console.log(`${e.message} :: $`);
                        });
                    }).catch((e) => {
                        console.log("Error trying to set polling frequency");
                        console.log(`${e.message} :: $`);
                    });
                }).catch((e) => {
                    console.log("Not claimed yet ...");
                });
            }
            catch (e) {
                console.log(`Not claimed :: ${e.message}`);
            }
        }
    }, 5000);
});
//# sourceMappingURL=index.js.map