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());
    });
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import { Box, Flex, Text } from "@theme-ui/components";
import { useEffect, useRef, useState } from "react";
import { Icons } from "../../toolbar";
import { Icon } from "@notesnook/ui";
import { DesktopOnly } from "../../components/responsive";
import { ToolbarGroup } from "../../toolbar/components/toolbar-group";
const FAILED_CONTENT = `<html><head>
<title>Failed to load web clip</title>
</head>
<body>
<p>Failed to load web clip</p>
</body>
</html>`;
export function WebClipComponent(props) {
    const { editor, selected, node, updateAttributes } = props;
    const [isLoading, setIsLoading] = useState(true);
    const embedRef = useRef(null);
    const resizeObserverRef = useRef();
    const { src, title, fullscreen, progress } = node.attrs;
    useEffect(() => {
        (function () {
            return __awaiter(this, void 0, void 0, function* () {
                var _a, _b;
                if (!isLoading)
                    return;
                const html = yield ((_b = (_a = editor.storage).getAttachmentData) === null || _b === void 0 ? void 0 : _b.call(_a, node.attrs).catch(() => null));
                const iframe = embedRef.current;
                if (!iframe || !iframe.contentDocument)
                    return;
                iframe.contentDocument.open();
                iframe.contentDocument.write(typeof html !== "string" || !html ? FAILED_CONTENT : html);
                iframe.contentDocument.close();
                iframe.contentDocument.head.innerHTML += `<base target="_blank">`;
                setIsLoading(false);
            });
        })();
    }, []);
    useEffect(() => {
        function fullscreenchanged() {
            var _a, _b, _c, _d, _e;
            if (document.fullscreenElement) {
                (_a = resizeObserverRef.current) === null || _a === void 0 ? void 0 : _a.disconnect();
                resetIframeSize(embedRef.current);
            }
            else {
                updateAttributes({ fullscreen: false });
                resizeIframe(node.attrs, embedRef.current);
                if ((_b = embedRef.current) === null || _b === void 0 ? void 0 : _b.contentDocument) {
                    (_c = resizeObserverRef.current) === null || _c === void 0 ? void 0 : _c.observe((_e = (_d = embedRef.current) === null || _d === void 0 ? void 0 : _d.contentDocument) === null || _e === void 0 ? void 0 : _e.body);
                }
            }
        }
        document.addEventListener("fullscreenchange", fullscreenchanged);
        return () => {
            document.removeEventListener("fullscreenchange", fullscreenchanged);
        };
    }, [updateAttributes]);
    useEffect(() => {
        var _a, _b, _c;
        if ((_a = embedRef.current) === null || _a === void 0 ? void 0 : _a.contentDocument) {
            resizeObserverRef.current = new ResizeObserver(() => {
                setTimeout(() => resizeIframe(node.attrs, embedRef.current), 100);
            });
            resizeObserverRef.current.observe((_c = (_b = embedRef.current) === null || _b === void 0 ? void 0 : _b.contentDocument) === null || _c === void 0 ? void 0 : _c.body);
        }
        return () => {
            var _a;
            (_a = resizeObserverRef.current) === null || _a === void 0 ? void 0 : _a.disconnect();
        };
    }, []);
    return (_jsx(_Fragment, { children: _jsxs(Box, { sx: {
                mt: 2,
                display: "flex",
                flexDirection: "column",
                position: "relative",
                border: selected
                    ? "2px solid var(--accent)"
                    : "2px solid var(--border)",
                borderRadius: "default"
            }, children: [_jsxs(Flex, { sx: {
                        width: "100%",
                        p: 1,
                        bg: "var(--background-secondary)",
                        borderTopLeftRadius: "default",
                        borderTopRightRadius: "default",
                        cursor: "pointer",
                        justifyContent: "space-between"
                    }, title: title, children: [_jsxs(Flex, { sx: { alignItems: "center" }, children: [_jsx(Icon, { path: Icons.webClip, size: 14, onClick: () => {
                                        window.open(src, "_blank", "noreferrer");
                                    } }), _jsx(Text, { variant: "subBody", sx: {
                                        ml: 1,
                                        whiteSpace: "nowrap",
                                        overflow: "hidden",
                                        textOverflow: "ellipsis"
                                    }, children: title })] }), _jsx(DesktopOnly, { children: selected && (_jsx(Flex, { sx: { position: "relative", justifyContent: "end" }, children: _jsx(Flex, { sx: {
                                        position: "absolute",
                                        top: -10,
                                        mb: 2,
                                        alignItems: "end"
                                    }, children: _jsx(ToolbarGroup, { editor: editor, tools: [
                                            "webclipFullScreen",
                                            "webclipOpenExternal",
                                            "webclipOpenSource"
                                        ], sx: {
                                            boxShadow: "menu",
                                            borderRadius: "default",
                                            bg: "background"
                                        } }) }) })) })] }), _jsx(Box, { sx: {
                        overflow: "hidden auto",
                        maxHeight: 1080
                    }, children: _jsx(Box, { sx: { overflow: "hidden" }, children: _jsx("iframe", { ref: embedRef, width: "auto", frameBorder: "0", scrolling: fullscreen ? "yes" : "no", style: { transformOrigin: "0 0", overflow: "hidden" }, onLoad: () => {
                                if (fullscreen)
                                    return;
                                resizeIframe(node.attrs, embedRef.current);
                            } }) }) }), isLoading && (_jsxs(Flex, { sx: {
                        position: "absolute",
                        bottom: 0,
                        width: "100%",
                        height: "calc(100% - 20px)",
                        alignItems: "center",
                        justifyContent: "center",
                        flexDirection: "column"
                    }, children: [_jsx(Icon, { path: Icons.loading, rotate: true, size: 32 }), progress ? (_jsxs(Text, { sx: { mt: 2 }, children: ["Loading web clip (", progress, "%)"] })) : null] }))] }) }));
}
function resizeIframe(attributes, iframe) {
    if (!iframe || !iframe.contentDocument || !iframe.contentDocument.body)
        return;
    const height = attributes.height
        ? parseInt(attributes.height)
        : iframe.contentDocument.body.scrollHeight;
    const width = attributes.width
        ? parseInt(attributes.width)
        : iframe.contentDocument.body.scrollWidth;
    iframe.style.height = `${height}px`;
    iframe.style.width = `${width}px`;
    const container = iframe.parentElement;
    if (!container || container.clientWidth > width)
        return;
    const scale = container.clientWidth / width;
    iframe.style.scale = `${scale}`;
    container.style.height = `${height * scale}px`;
}
function resetIframeSize(iframe) {
    if (!iframe || !iframe.contentDocument || !iframe.contentDocument.body)
        return;
    const height = iframe.contentDocument.body.scrollHeight;
    const width = iframe.contentDocument.body.scrollWidth;
    iframe.style.height = `${height}px`;
    iframe.style.width = `${width}px`;
    iframe.style.scale = `1`;
}
