var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
import React, { useEffect, useState, useCallback } from "react";
import { useStliteKernel } from "../StliteKernelProvider";
import { extractCustomComponentPath, getParentPath } from "./url";
import { manipulateIFrameDocument } from "./iframe-manipulation";
const InnerIFrame = React.forwardRef((_a, ref) => {
    var { src: path } = _a, props = __rest(_a, ["src"]);
    const kernel = useStliteKernel();
    const [srcdoc, setSrcdoc] = useState();
    useEffect(() => {
        if (kernel == null) {
            return;
        }
        if (!path.startsWith("/component")) {
            return;
        }
        let released = false;
        kernel
            .sendHttpRequest({
            method: "GET",
            path: path,
            headers: {},
            body: "",
        })
            .then(({ statusCode, headers, body }) => {
            if (released) {
                return;
            }
            if (statusCode !== 200) {
                return;
            }
            const blob = new Blob([body], { type: headers.get("Content-Type") });
            blob.text().then((text) => {
                if (released) {
                    return;
                }
                setSrcdoc(text);
            });
        });
        return () => {
            released = true;
        };
    }, [kernel, path]);
    const handleIFrameLoad = useCallback((ev) => {
        var _a;
        const iframe = ev.target;
        const document = (_a = iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.document;
        if (document == null) {
            console.warn("document not found in iframe");
            return;
        }
        manipulateIFrameDocument(kernel, document, getParentPath(path));
    }, [kernel, path]);
    return (_jsx("iframe", Object.assign({}, props, { srcDoc: srcdoc, onLoad: handleIFrameLoad, ref: ref })));
});
InnerIFrame.displayName = "InnerIFrame";
const CustomComponentIFrame = React.forwardRef((props, ref) => {
    const kernel = useStliteKernel();
    const path = extractCustomComponentPath(kernel.basePath, props.src);
    if (path == null) {
        return _jsx("iframe", Object.assign({}, props, { ref: ref }));
    }
    return _jsx(InnerIFrame, Object.assign({}, props, { src: path, ref: ref }));
});
CustomComponentIFrame.displayName = "StliteCustomComponentIFrame";
export default CustomComponentIFrame;
//# sourceMappingURL=index.js.map