"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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestiaEditorIframe = NestiaEditorIframe;
var jsx_runtime_1 = require("react/jsx-runtime");
var material_1 = require("@mui/material");
var sdk_1 = __importDefault(require("@stackblitz/sdk"));
var js_yaml_1 = require("js-yaml");
var react_1 = __importDefault(require("react"));
var NestiaEditorComposer_1 = require("./internal/NestiaEditorComposer");
function NestiaEditorIframe(props) {
    var _this = this;
    var _a = __read(react_1.default.useState("reactia-editor-div-".concat(Math.random().toString().substring(2))), 1), id = _a[0];
    var _b = __read(react_1.default.useState(0), 2), step = _b[0], setStep = _b[1];
    var _c = __read(react_1.default.useState(null), 2), fetchError = _c[0], setFetchError = _c[1];
    var _d = __read(react_1.default.useState({}), 2), operations = _d[0], setOperationCount = _d[1];
    var _e = __read(react_1.default.useState(null), 2), composerError = _e[0], setComposerError = _e[1];
    react_1.default.useEffect(function () {
        (function () { return __awaiter(_this, void 0, void 0, function () {
            var document, _a, result;
            var _this = this;
            var _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        // LOADING OPENAPI DOCUMENTS
                        setStep(0);
                        if (!(typeof props.swagger === "string")) return [3 /*break*/, 2];
                        return [4 /*yield*/, getDocument(props.swagger)];
                    case 1:
                        _a = _d.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        _a = props.swagger;
                        _d.label = 3;
                    case 3:
                        document = _a;
                        if (typeof document === "string") {
                            setFetchError(document);
                            return [2 /*return*/];
                        }
                        else
                            setOperationCount(aggregateOperation(document));
                        // GENERATING SOFTWARE DEVELOPMENT KIT
                        setStep(1);
                        return [4 /*yield*/, (function () { return __awaiter(_this, void 0, void 0, function () {
                                var exp_1;
                                var _a, _b, _c, _d, _e;
                                return __generator(this, function (_f) {
                                    switch (_f.label) {
                                        case 0:
                                            _f.trys.push([0, 2, , 3]);
                                            return [4 /*yield*/, NestiaEditorComposer_1.NestiaEditorComposer[(_a = props.mode) !== null && _a !== void 0 ? _a : "sdk"]({
                                                    document: document,
                                                    keyword: (_b = props.keyword) !== null && _b !== void 0 ? _b : true,
                                                    simulate: (_c = props.simulate) !== null && _c !== void 0 ? _c : true,
                                                    e2e: (_d = props.e2e) !== null && _d !== void 0 ? _d : true,
                                                    package: (_e = props.package) !== null && _e !== void 0 ? _e : "@ORGANIZATION/PROJECT",
                                                })];
                                        case 1: return [2 /*return*/, _f.sent()];
                                        case 2:
                                            exp_1 = _f.sent();
                                            return [2 /*return*/, {
                                                    success: false,
                                                    errors: exp_1,
                                                    data: undefined,
                                                }];
                                        case 3: return [2 /*return*/];
                                    }
                                });
                            }); })()];
                    case 4:
                        result = _d.sent();
                        if (result.success === false) {
                            setComposerError(result.errors);
                            return [2 /*return*/];
                        }
                        // COMPOSING STACKBLITZ PROJECT
                        setStep(2);
                        sdk_1.default.embedProject(id, {
                            title: (_c = (_b = document.info) === null || _b === void 0 ? void 0 : _b.title) !== null && _c !== void 0 ? _c : "Nestia Editor",
                            template: "node",
                            files: result.data.files,
                        }, {
                            width: "100%",
                            height: "100%",
                            openFile: result.data.openFile,
                            startScript: result.data.startScript, // no problem
                        });
                        return [2 /*return*/];
                }
            });
        }); })().catch(function (exp) {
            console.error("unknown error", exp);
        });
    }, []);
    return ((0, jsx_runtime_1.jsx)("div", { id: id, style: {
            width: "100%",
            height: "100%",
            overflow: "hidden",
        }, children: (0, jsx_runtime_1.jsxs)("div", { style: {
                padding: 25,
                overflow: "auto",
            }, children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "h4", children: "Nestia Editor" }), (0, jsx_runtime_1.jsx)("hr", {}), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsxs)(material_1.Stepper, { activeStep: step, orientation: "vertical", nonLinear: true, children: [(0, jsx_runtime_1.jsxs)(material_1.Step, { children: [(0, jsx_runtime_1.jsx)(material_1.StepLabel, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "h5", children: "Loading OpenAPI Document" }) }), (0, jsx_runtime_1.jsxs)(material_1.StepContent, { children: [(0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(material_1.CircularProgress, { size: 100, color: "success" }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)("br", {}), typeof props.swagger === "string" ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("p", { children: "Fetching OpenAPI Document from" }), (0, jsx_runtime_1.jsx)("p", { children: (0, jsx_runtime_1.jsx)("a", { href: props.swagger, target: "_blank", children: props.swagger }) })] })) : ("Delivering OpenAPI Document to the composer"), fetchError !== null ? ((0, jsx_runtime_1.jsxs)(material_1.Alert, { severity: "error", children: [(0, jsx_runtime_1.jsx)(material_1.AlertTitle, { children: "Fetch Error" }), fetchError] })) : null] })] }, 0), (0, jsx_runtime_1.jsxs)(material_1.Step, { children: [(0, jsx_runtime_1.jsx)(material_1.StepLabel, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "h5", children: "Generating Software Development Kit" }) }), (0, jsx_runtime_1.jsxs)(material_1.StepContent, { children: [(0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(material_1.CircularProgress, { size: 100, color: "success" }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)("br", {}), "Generating SDK functions...", (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsxs)("ul", { children: [(0, jsx_runtime_1.jsxs)("li", { children: ["total operations: #", Object.values(operations)
                                                            .reduce(function (a, b) { return a + b; }, 0)
                                                            .toLocaleString()] }), Object.entries(operations).map(function (_a) {
                                                    var _b = __read(_a, 2), method = _b[0], count = _b[1];
                                                    return ((0, jsx_runtime_1.jsxs)("li", { children: [method, ": #", count.toLocaleString()] }));
                                                })] }), composerError !== null ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsxs)(material_1.Alert, { severity: "error", children: [(0, jsx_runtime_1.jsx)(material_1.AlertTitle, { children: "Composition Error" }), (0, jsx_runtime_1.jsx)("pre", { children: JSON.stringify(composerError, null, 2) })] })] })) : null] })] }, 1), (0, jsx_runtime_1.jsxs)(material_1.Step, { children: [(0, jsx_runtime_1.jsx)(material_1.StepLabel, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "h5", children: "Composing TypeScript Project" }) }), (0, jsx_runtime_1.jsx)(material_1.StepContent, {})] }, 2)] })] }) }));
}
var getDocument = function (url) { return __awaiter(void 0, void 0, void 0, function () {
    var response, text, error_1;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 7, , 8]);
                return [4 /*yield*/, fetch(url)];
            case 1:
                response = _a.sent();
                if (!(response.status !== 200)) return [3 /*break*/, 3];
                return [4 /*yield*/, response.text()];
            case 2: return [2 /*return*/, _a.sent()];
            case 3:
                if (!url.endsWith(".yaml")) return [3 /*break*/, 5];
                return [4 /*yield*/, response.text()];
            case 4:
                text = _a.sent();
                return [2 /*return*/, (0, js_yaml_1.load)(text)];
            case 5: return [4 /*yield*/, response.json()];
            case 6: return [2 /*return*/, _a.sent()];
            case 7:
                error_1 = _a.sent();
                if (error_1 instanceof Error)
                    return [2 /*return*/, error_1.message];
                return [2 /*return*/, "Unknown error"];
            case 8: return [2 /*return*/];
        }
    });
}); };
var aggregateOperation = function (document) {
    var e_1, _a, e_2, _b;
    var _c, _d;
    var map = {};
    if (!(typeof document === "object" && document !== null))
        return map;
    try {
        for (var _e = __values(Object.values((_c = document.paths) !== null && _c !== void 0 ? _c : {})), _f = _e.next(); !_f.done; _f = _e.next()) {
            var collection = _f.value;
            if (typeof collection === "object" && collection !== null)
                try {
                    for (var _g = (e_2 = void 0, __values(Object.entries(collection))), _h = _g.next(); !_h.done; _h = _g.next()) {
                        var _j = __read(_h.value, 1), method = _j[0];
                        if (method === "head" ||
                            method === "get" ||
                            method === "post" ||
                            method === "patch" ||
                            method === "put" ||
                            method === "delete")
                            map[method] = ((_d = map[method]) !== null && _d !== void 0 ? _d : 0) + 1;
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return map;
};
//# sourceMappingURL=NestiaEditorIframe.js.map