"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.INSERT_IMAGE_COMMAND = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const lexical_1 = require("lexical");
const utils_1 = require("@lexical/utils");
const LexicalComposerContext_1 = require("@lexical/react/LexicalComposerContext");
const material_1 = require("@mui/material");
const styles_1 = require("@mui/material/styles");
const chunked_uploady_1 = tslib_1.__importDefault(require("@rpldy/chunked-uploady"));
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const MediaChunkUploader_1 = tslib_1.__importDefault(require("../../../shared/MediaChunkUploader"));
const upload_button_1 = require("@rpldy/upload-button");
const notistack_1 = require("notistack");
const ImageNode_1 = require("../nodes/ImageNode");
const constants_1 = require("../constants");
exports.INSERT_IMAGE_COMMAND = (0, lexical_1.createCommand)();
const UploadButton = (0, upload_button_1.asUploadButton)((0, react_1.forwardRef)((_a, ref) => {
    var { progress = null } = _a, rest = tslib_1.__rest(_a, ["progress"]);
    return ((0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({}, rest, { "aria-label": "upload image", ref: ref }, { children: progress ? (0, jsx_runtime_1.jsx)(material_1.CircularProgress, { variant: "determinate", value: progress, size: "1rem" }) : (0, jsx_runtime_1.jsx)(material_1.Icon, Object.assign({ color: "inherit" }, { children: "image" })) })));
}));
function Image({ editor, className = '' }) {
    // CONTEXT
    const scContext = (0, react_core_1.useSCContext)();
    const scUserContext = (0, react_core_1.useSCUser)();
    // STATE
    const [uploading, setUploading] = (0, react_1.useState)({});
    // HOOKS
    const { enqueueSnackbar } = (0, notistack_1.useSnackbar)();
    // HANDLERS
    const handleFileUploadFilter = (file, index, a) => {
        return file.type.startsWith('image/');
    };
    const handleUploadSuccess = (media) => {
        const data = {
            altText: media.title,
            src: media.image,
            width: media.image_width,
            height: media.image_height
        };
        editor.focus();
        editor.dispatchCommand(exports.INSERT_IMAGE_COMMAND, data);
    };
    const handleUploadProgress = (chunks) => {
        setUploading(Object.assign({}, chunks));
    };
    const handleUploadError = (chunk, error) => {
        enqueueSnackbar(error, {
            variant: 'error',
            autoHideDuration: 3000
        });
    };
    if (!scUserContext.user) {
        return null;
    }
    return ((0, jsx_runtime_1.jsxs)(chunked_uploady_1.default, Object.assign({ destination: {
            url: `${scContext.settings.portal}${api_services_1.Endpoints.ComposerChunkUploadMedia.url()}`,
            headers: Object.assign({}, (scContext.settings.session &&
                scContext.settings.session.authToken && {
                Authorization: `Bearer ${scContext.settings.session.authToken.accessToken}`
            })),
            method: api_services_1.Endpoints.ComposerChunkUploadMedia.method
        }, chunkSize: 204800, multiple: true, accept: "image/*", fileFilter: handleFileUploadFilter }, { children: [(0, jsx_runtime_1.jsx)(MediaChunkUploader_1.default, { type: "eimage", onSuccess: handleUploadSuccess, onProgress: handleUploadProgress, onError: handleUploadError }), (0, jsx_runtime_1.jsx)(UploadButton, { className: className, extraProps: {
                    disabled: Object.keys(uploading).length !== 0,
                    progress: Object.keys(uploading).length !== 0 ? Object.values(uploading)[0].completed : null
                } })] })));
}
const classes = {
    root: `${constants_1.PREFIX}-image-plugin-root`
};
const Root = (0, styles_1.styled)(Image, {
    name: constants_1.PREFIX,
    slot: 'ImagePluginRoot'
})(() => ({}));
function ImagePlugin() {
    const [editor] = (0, LexicalComposerContext_1.useLexicalComposerContext)();
    (0, react_1.useEffect)(() => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        if (!editor.hasNodes([ImageNode_1.ImageNode])) {
            return;
        }
        return editor.registerCommand(exports.INSERT_IMAGE_COMMAND, (payload) => {
            const imageNode = (0, ImageNode_1.$createImageNode)({
                src: payload.src,
                altText: payload.altText,
                maxWidth: '100%',
                width: payload.width,
                height: payload.height
            });
            // The image is not editable so it is better to position it near the root element
            (0, utils_1.$insertNodeToNearestRoot)(imageNode);
            return true;
        }, lexical_1.COMMAND_PRIORITY_EDITOR);
    }, [editor]);
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    if (!editor.hasNodes([ImageNode_1.ImageNode])) {
        return null;
    }
    return (0, jsx_runtime_1.jsx)(Root, { editor: editor, className: classes.root });
}
exports.default = ImagePlugin;
