"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 });
exports.jsonParser = void 0;
const express_1 = __importDefault(require("express"));
const body_parser_1 = __importDefault(require("body-parser"));
const path_1 = __importDefault(require("path"));
const compiler_1 = require("../controllers/compiler");
const workspace_1 = require("../controllers/workspace");
const utils_1 = require("../utils");
const cliconfig_1 = require("../database/cliconfig");
const form_data_1 = __importDefault(require("form-data"));
const axios_1 = __importDefault(require("axios"));
const websocket_1 = require("../websocket");
exports.jsonParser = body_parser_1.default.json({ limit: "50mb" });
const router = express_1.default.Router();
//Middleware to check the open app and inject the available cookie into headers
const checkAppInfo = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const customReq = req;
    const appId = customReq.params.appid;
    try {
        const apptileConfig = yield (0, workspace_1.getAppConfigsFromFS)(appId);
        const openedApp = yield (0, cliconfig_1.getOpenApp)(appId);
        if (!openedApp) {
            res.status(400).send("No app is open");
        }
        if (!(openedApp === null || openedApp === void 0 ? void 0 : openedApp.apptilecookie)) {
            res.status(400).send("Apptile cookie not found in the opened app");
        }
        else {
            customReq.apptileCookie = openedApp.apptilecookie;
            customReq.APPTILE_BACKEND_URL = apptileConfig === null || apptileConfig === void 0 ? void 0 : apptileConfig.APPTILE_BACKEND_URL;
            req = Object.assign(req, customReq);
            next();
        }
    }
    catch (err) {
        res.status(400).send(err === null || err === void 0 ? void 0 : err.message);
        next(err);
    }
});
router.get(`/currentWebSdkBundle`, (req, res) => {
    const currentBundlePath = path_1.default.resolve(__dirname, '../dist/web-sdk-bundle.js');
    res.sendFile(currentBundlePath);
});
router.get("/compile", (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const sourceFolder = decodeURIComponent(req.query.sourceFolder);
        if (!sourceFolder) {
            res.status(400).send("sourceFolder is required");
        }
        const compiled = yield (0, compiler_1.compileWebSDK)(sourceFolder);
        (0, websocket_1.sendHotReloadRequest)();
        res.status(200).json(compiled);
    }
    catch (err) {
        console.error("Error compiling webSDK", err);
        res.status(400).send(err === null || err === void 0 ? void 0 : err.message);
        next(err);
    }
}));
router.post("/:appid/live/:artifactId", checkAppInfo, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    // Upload websdk bundle
    const customReq = req;
    let formData = new form_data_1.default();
    let headers = {};
    const artifactId = req.params.artifactId;
    headers = (0, utils_1.makeHeadersWithCookie)(customReq.apptileCookie, formData.getHeaders());
    try {
        let response = yield axios_1.default
            .post(`${customReq.APPTILE_BACKEND_URL}/api/web-sdk/live/${artifactId}`, formData, headers)
            .catch((err) => {
            console.error("Error making latest live", err);
            throw err;
        });
        if (response.status >= 400) {
            try {
                const erroMessage = response.data;
                throw new Error("Failed to make live " + erroMessage);
            }
            catch (err) {
                console.error("Unprocessable error: ", err);
                throw err;
            }
        }
        (0, websocket_1.sendLog)(`Bundle ${artifactId} made live successfully: ${JSON.stringify(response.data, null, 2)}`);
        res.status(200).send("Done");
    }
    catch (error) {
        console.error("Error making latest live", error);
        next(error);
    }
}));
//Get available partners
router.get("/:appid/partners", checkAppInfo, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const customReq = req;
    try {
        let formData = new form_data_1.default();
        const headers = (0, utils_1.makeHeadersWithCookie)(customReq.apptileCookie, formData.getHeaders());
        try {
            let response = yield axios_1.default
                .get(`${customReq.APPTILE_BACKEND_URL}/api/web-sdk/partners`, headers)
                .catch((err) => {
                console.error("Error making latest live", err);
                throw err;
            });
            if (response.status >= 400) {
                try {
                    const erroMessage = response.data;
                    throw new Error("Failed to fetch " + erroMessage);
                }
                catch (err) {
                    console.error("Unprocessable error: ", err);
                    throw err;
                }
            }
            res.status(200).send(response.data);
            (0, websocket_1.sendLog)("Partners fetched successfully");
        }
        catch (error) {
            (0, websocket_1.sendLog)(`Error fetching partners ${error}`);
            next(error);
        }
    }
    catch (err) {
        res.status(400).send(err === null || err === void 0 ? void 0 : err.message);
        next(err);
    }
}));
router.get("/:appid/bundles/:partner", checkAppInfo, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const customReq = req;
    let formData = new form_data_1.default();
    const partner = req.params.partner;
    try {
        if (!partner) {
            res.status(400).send("partner is required");
        }
        const headers = (0, utils_1.makeHeadersWithCookie)(customReq.apptileCookie, formData.getHeaders());
        try {
            let response = yield axios_1.default
                .get(`${customReq.APPTILE_BACKEND_URL}/api/web-sdk/bundles/${partner}`, headers)
                .catch((err) => {
                console.error("Error making latest live", err);
                throw err;
            });
            if (response.status >= 400) {
                try {
                    const erroMessage = response.data;
                    throw new Error("Failed to fetch " + erroMessage);
                }
                catch (err) {
                    console.error("Unprocessable error: ", err);
                    throw err;
                }
            }
            res.status(200).send(response.data);
            (0, websocket_1.sendLog)("Bundles fetched successfully");
        }
        catch (error) {
            (0, websocket_1.sendLog)(`Error fetching bundles ${error}`);
            next(error);
        }
    }
    catch (err) {
        res.status(400).send(err === null || err === void 0 ? void 0 : err.message);
        next(err);
    }
}));
router.get("/:appid/live/:partner", checkAppInfo, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const customReq = req;
    let formData = new form_data_1.default();
    const partner = req.params.partner;
    try {
        if (!partner) {
            res.status(400).send("partner is required");
        }
        const headers = (0, utils_1.makeHeadersWithCookie)(customReq.apptileCookie, formData.getHeaders());
        try {
            let response = yield axios_1.default
                .get(`${customReq.APPTILE_BACKEND_URL}/api/web-sdk/live/${partner}`, headers)
                .catch((err) => {
                console.error("Error making latest live", err);
                throw err;
            });
            if (response.status >= 400) {
                try {
                    const erroMessage = response.data;
                    throw new Error("Failed to fetch " + erroMessage);
                }
                catch (err) {
                    console.error("Unprocessable error: ", err);
                    throw err;
                }
            }
            res.status(200).send(response.data);
            (0, websocket_1.sendLog)("Bundles fetched successfully");
        }
        catch (error) {
            (0, websocket_1.sendLog)(`Error fetching bundles ${error}`);
            next(error);
        }
    }
    catch (err) {
        res.status(400).send(err === null || err === void 0 ? void 0 : err.message);
        next(err);
    }
}));
router.get("/:appid/upload/:partner", checkAppInfo, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const customReq = req;
    const partner = req.params.partner;
    try {
        const webSDKBundle = yield (0, workspace_1.getWebSDKBundleFromFS)();
        if (!webSDKBundle) {
            res.render("error", { message: "Failed to get webSDK bundle" });
        }
        else {
            // Upload websdk bundle
            let formData = new form_data_1.default();
            formData.append("file", webSDKBundle);
            formData.append("uploadDestination", "plugins");
            let headers = {};
            headers = (0, utils_1.makeHeadersWithCookie)(customReq.apptileCookie, formData.getHeaders());
            const response = yield axios_1.default
                .post(`${customReq.APPTILE_BACKEND_URL}/api/web-sdk/upload?partner=${partner}`, formData, headers)
                .catch((err) => {
                console.error("Error uploading webSDK bundle", err);
                throw err;
            });
            if (response.status < 400) {
                res.status(200).send(response.data);
                (0, websocket_1.sendLog)(`WebSDK bundle uploaded successfully: ${JSON.stringify(response.data, null, 2)}`);
            }
            if (response.status >= 400) {
                try {
                    const erroMessage = response.data;
                    throw new Error("Failed to upload " + erroMessage);
                }
                catch (err) {
                    console.error("Unprocessable error: ", err);
                    throw err;
                }
            }
        }
    }
    catch (err) {
        console.error("in uploadWebBundles", err === null || err === void 0 ? void 0 : err.message);
        next(err);
    }
}));
exports.default = router;
