"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.thk_router = void 0;
const express_1 = require("express");
const express_async_handler_1 = __importDefault(require("express-async-handler"));
function thk_router(language, renderPage, _logger) {
    async function thk(req, res, _next) {
        req.apiClient.accessToken = req.query.t;
        console.log(req.apiClient.accessToken);
        try {
            const { thkGroup } = await getThkGroup();
            const thks = await Promise.all(thkGroup.devices.map((d) => req.apiClient.getDevice(d.url)));
            return renderPage("thk", language, res, req.user, {
                thks,
            });
        }
        catch {
            return renderPage("thk", language, res, req.user, {
                thks: [],
            });
        }
        async function getThkGroup() {
            const devices = await req.apiClient.listDevices();
            const deviceGroups = devices.filter((d) => d.type === "group");
            console.log(deviceGroups);
            const thkGroupUrl = deviceGroups.find((d) => d.name.toLowerCase() === "thk")?.url;
            if (!thkGroupUrl) {
                throw new Error("Could not find thk group");
            }
            const thkGroup = await req.apiClient.getDevice(thkGroupUrl);
            if (thkGroup.type !== "group") {
                throw new Error("Device is not a group");
            }
            return { thkGroup };
        }
    }
    const router = (0, express_1.Router)();
    router.get("/thk", (0, express_async_handler_1.default)(thk));
    return router;
}
exports.thk_router = thk_router;
//# sourceMappingURL=thk.js.map