var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import ReactResizeDetector from 'react-resize-detector';
import Typography from '@mui/material/Typography';
import { insertDefaultImageByAttrUri } from '@reltio/mdm-sdk';
import { BlockImageGalleryDialogContext } from '../contexts/BlockImageGalleryDialogContext';
import { useMdmAction, useMdmEntity, useMdmIsViewMode } from '../contexts/MdmModuleContext';
import { ImageAttributesGallery } from '../ImageAttributesGallery';
import { DEFAULT_IMAGE_SIZE, IMAGE_MIN_VISIBLE_WIDTH } from './constants';
import { downloadImagesByURLs } from './helpers';
import { useStyles } from './styles';
export var ImageAttributesLine = function (_a) {
    var attributeType = _a.attributeType, _b = _a.attributeValues, attributeValues = _b === void 0 ? [] : _b, renderImage = _a.renderImage, _c = _a.overlay, overlay = _c === void 0 ? false : _c, _d = _a.countFixedItems, countFixedItems = _d === void 0 ? 0 : _d, children = _a.children, onUpload = _a.onUpload, onDeleteAttribute = _a.onDeleteAttribute, _e = _a.imageSize, imageSize = _e === void 0 ? DEFAULT_IMAGE_SIZE : _e, paging = _a.paging, parentUri = _a.parentUri, showNonOv = _a.showNonOv, requestNextPageOfAttributeValues = _a.requestNextPageOfAttributeValues;
    var styles = useStyles(imageSize);
    useEffect(function () {
        if (paging && requestNextPageOfAttributeValues) {
            var totalVisibleValues = showNonOv ? paging.totalOvValues : paging.totalValues;
            if (totalVisibleValues > attributeValues.length) {
                requestNextPageOfAttributeValues({
                    parentUri: parentUri,
                    attributeTypeUri: attributeType.uri,
                    attributeTypeName: attributeType.name,
                    values: [],
                    defaultMaxValues: totalVisibleValues
                });
            }
        }
    }, [paging, requestNextPageOfAttributeValues, attributeType, parentUri, attributeValues.length, showNonOv]);
    var lastWidth = useRef();
    var _f = useState(attributeValues.length), maxItems = _f[0], setMaxItems = _f[1];
    var _g = useState(0), hiddenItemsLength = _g[0], setHiddenItemsLength = _g[1];
    var isBlockImageGalleryDialog = useContext(BlockImageGalleryDialogContext);
    var _h = useState(false), isOpenDialog = _h[0], setIsOpenDialog = _h[1];
    var _j = useState(), currentAttributeValueUri = _j[0], setCurrentAttributeValueUri = _j[1];
    var setDefaultProfilePicForEntity = useMdmAction('setDefaultProfilePicForEntity');
    var setDefaultProfilePicForModifiedEntity = useMdmAction('setDefaultProfilePicForModifiedEntity');
    var entity = useMdmEntity() || {};
    var isViewMode = useMdmIsViewMode();
    var adjustMaxItemsToScreenWidth = useCallback(function (width) {
        var imageMargin = imageSize.imageMargin, imageWidth = imageSize.imageWidth;
        var maxItemsPerScreen = Math.floor((width + imageMargin) / (imageWidth + imageMargin)) - countFixedItems;
        var hasHiddenImage = width + imageMargin - (maxItemsPerScreen + countFixedItems) * (imageWidth + imageMargin) <
            IMAGE_MIN_VISIBLE_WIDTH;
        setMaxItems(maxItemsPerScreen);
        if (attributeValues.length > maxItemsPerScreen) {
            setHiddenItemsLength(attributeValues.length - maxItemsPerScreen + (hasHiddenImage ? 1 : 0));
        }
        else {
            setHiddenItemsLength(0);
        }
    }, [attributeValues.length, countFixedItems, imageSize]);
    var handleResize = useCallback(function (width) {
        adjustMaxItemsToScreenWidth(width);
        lastWidth.current = width;
    }, [adjustMaxItemsToScreenWidth]);
    useEffect(function () {
        if (lastWidth.current) {
            adjustMaxItemsToScreenWidth(lastWidth.current);
        }
    }, [attributeValues.length, adjustMaxItemsToScreenWidth]);
    var handleOpenImageGalleryDialog = useCallback(function (uri) {
        if (!isBlockImageGalleryDialog) {
            setCurrentAttributeValueUri(uri);
            setIsOpenDialog(true);
        }
    }, [isBlockImageGalleryDialog]);
    var handleCloseImageGalleryDialog = useCallback(function () {
        setIsOpenDialog(false);
    }, []);
    var handleDownload = function (urls) { return downloadImagesByURLs(urls); };
    var handleShareLink = function (url) { return navigator.clipboard.writeText(url); };
    var handleSetAsDefault = useCallback(function (attributeValue) {
        if (isViewMode) {
            insertDefaultImageByAttrUri(entity.uri, attributeValue.uri).then(function (_a) {
                var status = _a.status;
                if (status === 'success') {
                    setDefaultProfilePicForEntity(attributeValue);
                }
            });
        }
        else {
            setDefaultProfilePicForModifiedEntity({
                entityUri: entity.uri,
                value: attributeValue
            });
        }
    }, [isViewMode, entity.uri, setDefaultProfilePicForEntity, setDefaultProfilePicForModifiedEntity]);
    var renderImageProps = __assign({ onOpenImageGalleryDialog: handleOpenImageGalleryDialog }, (overlay && {
        onDownload: handleDownload,
        onShareLink: handleShareLink,
        onSetAsDefault: handleSetAsDefault
    }));
    return (React.createElement(React.Fragment, null,
        React.createElement(ReactResizeDetector, { handleWidth: true, handleHeight: false, onResize: handleResize, refreshMode: "debounce", refreshRate: 50 }),
        React.createElement(ImageAttributesGallery, { attributeValues: attributeValues, open: isOpenDialog, onClose: handleCloseImageGalleryDialog, setCurrentAttributeValueUri: setCurrentAttributeValueUri, currentAttributeValueUri: currentAttributeValueUri, attributeType: attributeType, onDownload: handleDownload, onShareLink: handleShareLink, onSetAsDefault: handleSetAsDefault, onUpload: onUpload, onDeleteAttribute: onDeleteAttribute }),
        React.createElement("div", { className: styles.imageBox },
            children,
            attributeValues.slice(0, maxItems).map(renderImage(renderImageProps)),
            hiddenItemsLength > 0 && (React.createElement("div", { className: styles.moreButtonContainer },
                React.createElement("div", { "data-reltio-id": "more-image-button", className: styles.moreButton, onClick: function () { return handleOpenImageGalleryDialog(); } },
                    React.createElement(Typography, { className: styles.number }, "+".concat(hiddenItemsLength))))))));
};
