// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
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 { Icon, TooltipHost } from '@fluentui/react';
import { Card, CardHeader, Text, Menu, MenuTrigger, ToolbarButton, MenuPopover, MenuItem, MenuList, Toolbar, CardFooter, ProgressBar, mergeClasses } from '@fluentui/react-components';
import { getFileTypeIconProps } from '@fluentui/react-file-type-icons';
import React from 'react';
import { Announcer } from '../Announcer';
import { useEffect, useState, useMemo } from 'react';
import { useLocaleAttachmentCardStringsTrampoline } from '../utils/common';
import { useAttachmentCardStyles, ATTACHMENT_CARD_MIN_PROGRESS, titleTooltipContainerStyle } from '../styles/AttachmentCard.styles';
/**
 * @internal
 * A component for displaying an attachment card with attachment icon and progress bar.
 *
 * `_AttachmentCard` internally uses the `Card` component from `@fluentui/react-components`. You can checkout the details about these components [here](https://react.fluentui.dev/?path=/docs/components-card).
 */
export const _AttachmentCard = (props) => {
    var _a, _b, _c, _d, _e;
    const { attachment, menuActions, onActionHandlerFailed, selfResizing } = props;
    const attachmentCardStyles = useAttachmentCardStyles();
    const progress = useMemo(() => {
        return 'progress' in attachment ? attachment.progress : undefined;
    }, [attachment]);
    const isUploadInProgress = useMemo(() => {
        return progress !== undefined && progress >= 0 && progress < 1;
    }, [progress]);
    const [announcerString, setAnnouncerString] = useState(undefined);
    const localeStrings = useLocaleAttachmentCardStringsTrampoline();
    const uploadStartedString = (_b = (_a = props.strings) === null || _a === void 0 ? void 0 : _a.uploading) !== null && _b !== void 0 ? _b : localeStrings.uploading;
    const uploadCompletedString = (_d = (_c = props.strings) === null || _c === void 0 ? void 0 : _c.uploadCompleted) !== null && _d !== void 0 ? _d : localeStrings.uploadCompleted;
    useEffect(() => {
        if (isUploadInProgress) {
            setAnnouncerString(`${uploadStartedString} ${attachment.name}`);
        }
        else if (progress === 1) {
            setAnnouncerString(`${attachment.name} ${uploadCompletedString}`);
        }
        else {
            setAnnouncerString(undefined);
        }
    }, [progress, isUploadInProgress, attachment.name, uploadStartedString, uploadCompletedString]);
    const extension = useMemo(() => {
        const re = /(?:\.([^.]+))?$/;
        const match = re.exec(attachment.name);
        return match && match[1] ? match[1] : '';
    }, [attachment]);
    return React.createElement("div", { "data-is-focusable": true },
        React.createElement(Card, { className: mergeClasses(attachmentCardStyles.root, selfResizing ? attachmentCardStyles.dynamicWidth : attachmentCardStyles.staticWidth), size: "small", role: "listitem", appearance: "filled-alternative", "aria-label": attachment.name, "data-testid": 'attachment-card' },
            React.createElement(Announcer, { announcementString: announcerString, ariaLive: 'polite' }),
            React.createElement(CardHeader, { className: attachmentCardStyles.content, image: {
                    className: attachmentCardStyles.fileIcon,
                    children: React.createElement(Icon, { "data-ui-id": 'attachmenttype-icon', iconName: getFileTypeIconProps({
                            extension: extension,
                            size: 24,
                            imageFileType: 'svg'
                        }).iconName })
                }, header: {
                    id: 'attachment-' + attachment.id,
                    children: React.createElement(TooltipHost, { content: attachment.name, calloutProps: {
                            gapSpace: 0,
                            target: '#attachment-' + attachment.id
                        }, hostClassName: titleTooltipContainerStyle },
                        React.createElement(Text, { className: attachmentCardStyles.title, "aria-label": attachment.name }, attachment.name))
                }, action: {
                    className: attachmentCardStyles.actions,
                    children: MappedMenuItems(menuActions, Object.assign(Object.assign({}, attachment), { url: (_e = attachment.url) !== null && _e !== void 0 ? _e : '' }), onActionHandlerFailed)
                } })),
        isUploadInProgress ? React.createElement(CardFooter, null,
            React.createElement(ProgressBar, { thickness: "medium", value: Math.max(progress !== null && progress !== void 0 ? progress : 0, ATTACHMENT_CARD_MIN_PROGRESS), shape: "rounded" })) : React.createElement(React.Fragment, null, " "));
};
const MappedMenuItems = (menuActions, attachment, handleOnClickError) => {
    const localeStrings = useLocaleAttachmentCardStringsTrampoline();
    const toolTipHostCloseDelayMs = 500;
    if (!menuActions[0]) {
        return React.createElement(React.Fragment, null);
    }
    return menuActions.length === 1 ? React.createElement(TooltipHost, { content: menuActions[0].name, closeDelay: toolTipHostCloseDelayMs },
        React.createElement(ToolbarButton, { "aria-label": menuActions[0].name, role: "button", icon: menuActions[0].icon, onClick: () => {
                var _a;
                try {
                    (_a = menuActions[0]) === null || _a === void 0 ? void 0 : _a.onClick(attachment);
                }
                catch (e) {
                    handleOnClickError === null || handleOnClickError === void 0 ? void 0 : handleOnClickError(e.message);
                }
            } })) : React.createElement(Toolbar, null,
        React.createElement(Menu, null,
            React.createElement(TooltipHost, { content: localeStrings.attachmentMoreMenu, closeDelay: toolTipHostCloseDelayMs },
                React.createElement(MenuTrigger, null,
                    React.createElement(ToolbarButton, { "aria-label": localeStrings.attachmentMoreMenu, role: "button", icon: React.createElement(Icon, { iconName: "AttachmentMoreMenu" }) }))),
            React.createElement(MenuPopover, null,
                React.createElement(MenuList, null, menuActions.map((menuItem, index) => React.createElement(MenuItem, { "aria-label": menuItem.name, key: index, icon: menuItem.icon, onClick: () => __awaiter(void 0, void 0, void 0, function* () {
                        try {
                            yield menuItem.onClick(attachment);
                        }
                        catch (e) {
                            handleOnClickError === null || handleOnClickError === void 0 ? void 0 : handleOnClickError(e.message);
                        }
                    }) }, menuItem.name))))));
};
//# sourceMappingURL=AttachmentCard.js.map