"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const upload_button_1 = require("@rpldy/upload-button");
const react_1 = tslib_1.__importStar(require("react"));
const material_1 = require("@mui/material");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const chunked_uploady_1 = tslib_1.__importDefault(require("@rpldy/chunked-uploady"));
const types_1 = require("@selfcommunity/types");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const styles_1 = require("@mui/material/styles");
const Widget_1 = tslib_1.__importDefault(require("../../Widget"));
const MessageChunkUploader_1 = tslib_1.__importDefault(require("../../../shared/MessageChunkUploader"));
const upload_drop_zone_1 = tslib_1.__importDefault(require("@rpldy/upload-drop-zone"));
const react_intl_1 = require("react-intl");
const thumbnailCoverter_1 = require("../../../utils/thumbnailCoverter");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const sizeCoverter_1 = require("../../../utils/sizeCoverter");
const constants_1 = require("../constants");
const MAX_FILE_SIZE = 10485760;
const UploadButton = (0, upload_button_1.asUploadButton)((0, react_1.forwardRef)((props, ref) => ((0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({}, props, { ref: ref, color: "inherit" }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "upload" }) })))));
const classes = {
    root: `${constants_1.PREFIX}-message-media-uploader-root`,
    uploadSection: `${constants_1.PREFIX}-upload-section`,
    uploadButton: `${constants_1.PREFIX}-upload-button`,
    closeButton: `${constants_1.PREFIX}-close-button`,
    previewContent: `${constants_1.PREFIX}-preview-content`,
    previewItem: `${constants_1.PREFIX}-preview-item`,
    previewActions: `${constants_1.PREFIX}-preview-actions`,
    progress: `${constants_1.PREFIX}-progress`,
    previewInfo: `${constants_1.PREFIX}-preview-info`
};
const Root = (0, styles_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'MessageMediaUploader'
})(() => ({}));
function MessageMediaUploader(props) {
    //PROPS
    const { className, forwardMessageFile, onClose, isUploading, action } = props;
    // STATE
    const [files, setFiles] = (0, react_1.useState)([]);
    const [uploading, setUploading] = (0, react_1.useState)({});
    const [previews, setPreviews] = (0, react_1.useState)([]);
    const [errors, setErrors] = (0, react_1.useState)({});
    const [isHovered, setIsHovered] = (0, react_1.useState)({});
    // CONTEXT
    const scContext = (0, react_1.useContext)(react_core_1.SCContext);
    // HANDLERS
    const update = (list, itemId) => {
        return list.filter((i) => i.file_uuid != itemId);
    };
    const handleClear = (itemId) => {
        if (itemId) {
            setPreviews((prev) => update(prev, itemId));
            setFiles((prev) => update(prev, itemId));
            forwardMessageFile(update(files, itemId));
        }
        else {
            setFiles([]);
            setPreviews([]);
            forwardMessageFile([]);
        }
        setUploading({});
    };
    const handleSuccess = (media) => {
        setFiles((prev) => [...prev, media]);
    };
    const forwardFiles = () => {
        forwardMessageFile(files);
    };
    const handleProgress = (chunks) => {
        setUploading(Object.assign({}, chunks));
        setPreviews([...files, ...Object.values(chunks)]);
        isUploading(Object.keys(chunks).length !== 0);
        Object.keys(chunks).length === 0 && Object.keys(uploading).length !== 0 && forwardFiles();
    };
    const handleError = (chunk, error) => {
        setErrors(Object.assign(Object.assign({}, errors), { [chunk.id]: Object.assign(Object.assign({}, chunk), { error }) }));
    };
    const handleRemoveErrors = (id) => {
        return () => {
            delete errors[id];
            setErrors(Object.assign({}, errors));
        };
    };
    const handleMouseEnter = (index) => {
        setIsHovered((prevState) => {
            return Object.assign(Object.assign({}, prevState), { [index]: true });
        });
    };
    const handleMouseLeave = (index) => {
        setIsHovered((prevState) => {
            return Object.assign(Object.assign({}, prevState), { [index]: false });
        });
    };
    const getMouseEvents = (mouseEnter, mouseLeave) => ({
        onMouseEnter: mouseEnter,
        onMouseLeave: mouseLeave,
        onTouchStart: mouseEnter,
        onTouchMove: mouseLeave
    });
    const filterBySizeAndType = (file) => {
        return file.size < MAX_FILE_SIZE;
    };
    /**
     * Renders root object
     */
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, { children: [(0, jsx_runtime_1.jsx)(material_1.CardHeader, { action: (0, jsx_runtime_1.jsx)(Icon_1.default, Object.assign({ onClick: onClose, className: classes.closeButton }, { children: "close" })) }), Object.keys(errors).map((id) => ((0, jsx_runtime_1.jsx)(material_1.Fade, Object.assign({ in: true }, { children: (0, jsx_runtime_1.jsxs)(material_1.Alert, Object.assign({ severity: "error", onClose: handleRemoveErrors(id) }, { children: [(0, jsx_runtime_1.jsx)(material_1.AlertTitle, { children: errors[id].name }), errors[id].error] })) }), id))), (0, jsx_runtime_1.jsx)(material_1.CardContent, { children: (0, jsx_runtime_1.jsxs)(chunked_uploady_1.default, Object.assign({ destination: {
                        url: `${scContext.settings.portal}${api_services_1.Endpoints.PrivateMessageUploadMediaInChunks.url()}`,
                        headers: { Authorization: `Bearer ${scContext.settings.session.authToken.accessToken}` },
                        method: api_services_1.Endpoints.PrivateMessageUploadMediaInChunks.method
                    }, chunkSize: 204800, multiple: true, chunked: true, maxConcurrent: 2, fileFilter: filterBySizeAndType }, { children: [(0, jsx_runtime_1.jsx)(MessageChunkUploader_1.default, { onSuccess: handleSuccess, onProgress: handleProgress, onError: handleError }), !files.length && Object.keys(uploading).length === 0 && Object.keys(errors).length === 0 && ((0, jsx_runtime_1.jsxs)(upload_drop_zone_1.default, Object.assign({ className: classes.uploadSection }, { children: [(0, jsx_runtime_1.jsx)(UploadButton, { inputFieldName: "file", className: classes.uploadButton }), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ textAlign: 'center', fontWeight: 'medium' }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.privateMessage.editor.media.uploader.msg", defaultMessage: "ui.privateMessage.editor.media.uploader.msg" }) }))] }))), (0, jsx_runtime_1.jsxs)(material_1.List, Object.assign({ className: classes.previewContent }, { children: [previews.length !== 0 &&
                                    previews.map((item, index) => {
                                        var _a;
                                        return ((0, jsx_runtime_1.jsx)(react_1.default.Fragment, { children: 'file' in item && ((0, jsx_runtime_1.jsxs)(material_1.ListItem, Object.assign({ className: classes.previewItem }, getMouseEvents(() => handleMouseEnter(item.file_uuid), () => handleMouseLeave(item.file_uuid)), { children: ['video_url' in item ? ((0, jsx_runtime_1.jsx)("video", { src: item.video_url })) : ((0, jsx_runtime_1.jsx)("img", { src: item.file.type.startsWith(types_1.SCMessageFileType.PDF) && !item.file_url
                                                            ? thumbnailCoverter_1.pdfImagePlaceholder
                                                            : !item.file_url
                                                                ? thumbnailCoverter_1.documentPlaceholder
                                                                : item.file_url })), (0, jsx_runtime_1.jsx)(material_1.ImageListItemBar, { className: (0, classnames_1.default)(classes.previewActions, { [classes.progress]: item.completed }), title: typeof item.completed !== 'undefined' &&
                                                            item.completed !== 0 && (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ textAlign: "center" }, { children: `${Math.round(item.completed)}%` })), actionIcon: (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: isHovered[item.file_uuid] && Object.keys(uploading).length === 0 && ((0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ onClick: () => handleClear(item.file_uuid), size: "small" }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "delete" }) }))) }) }), isHovered[item.file_uuid] && ((0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ component: 'span', className: classes.previewInfo }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ noWrap: true, textAlign: 'center' }, { children: item.file.name })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ textAlign: 'center', fontWeight: 'light' }, { children: (0, sizeCoverter_1.bytesToSize)(item.file.size) }))] })))] }), (_a = item.id) !== null && _a !== void 0 ? _a : item.file_uuid)) }, index));
                                    }), previews.length !== 0 && action] }))] })) })] })));
}
exports.default = MessageMediaUploader;
