"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const styles_1 = require("@mui/material/styles");
const material_1 = require("@mui/material");
const react_core_1 = require("@selfcommunity/react-core");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const react_intl_1 = require("react-intl");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const constants_1 = require("./constants");
const lab_1 = require("@mui/lab");
const api_services_1 = require("@selfcommunity/api-services");
const Errors_1 = require("../../constants/Errors");
const utils_1 = require("@selfcommunity/utils");
const classes = {
    root: `${constants_1.PREFIX}-root`
};
const Root = (0, styles_1.styled)(lab_1.LoadingButton, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
const messages = (0, react_intl_1.defineMessages)({
    errorLoadImage: {
        id: 'ui.changeGroupCover.button.change.alertErrorImage',
        defaultMessage: 'ui.changeGroupCover.button.change.alertErrorImage'
    },
    errorImageSize: {
        id: 'ui.changeGroupCover.alert',
        defaultMessage: 'ui.changeGroupCover.alert'
    }
});
/**
 * > API documentation for the Community-JS Change Group Cover component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a button that allows admins to edit the group cover and a popover that specifies format and sizes allowed.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/ChangeGroupCover)

 #### Import
 ```jsx
 import {ChangeGroupCover} from '@selfcommunity/react-ui';
 ```

 #### Component Name
 The name `SCChangeGroupCoverButton` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCChangeGroupCoverButton-root|Styles applied to the root element.|

 * @param inProps
 */
function ChangeGroupCover(inProps) {
    //PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { groupId, onChange, autoHide, className, isCreationMode = false } = props, rest = tslib_1.__rest(props, ["groupId", "onChange", "autoHide", "className", "isCreationMode"]);
    //CONTEXT
    const scUserContext = (0, react_1.useContext)(react_core_1.SCUserContext);
    //STATE
    let fileInput = (0, react_1.useRef)(null);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const [alert, setAlert] = (0, react_1.useState)(null);
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // Anonymous
    if (!scUserContext.user) {
        return null;
    }
    /**
     * Handles file upload
     * @param event
     */
    const handleUpload = (event) => {
        fileInput = event.target.files[0];
        if (fileInput) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    isCreationMode ? onChange && onChange(fileInput) : handleSave();
                    // if (img.width < 1920) {
                    //   setAlert(intl.formatMessage(messages.errorImageSize));
                    // } else {
                    //   isCreationMode ? onChange && onChange(fileInput) : handleSave();
                    // }
                };
                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                // @ts-ignore
                img.src = e.target.result;
            };
            // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
            // @ts-ignore
            reader.readAsDataURL(fileInput);
        }
    };
    /**
     * Handles cover saving after upload action
     */
    function handleSave() {
        setLoading(true);
        const formData = new FormData();
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        formData.append('emotional_image_original', fileInput);
        api_services_1.GroupService.changeGroupAvatarOrCover(groupId, formData, { headers: { 'Content-Type': 'multipart/form-data' } })
            .then((data) => {
            onChange && onChange(data.emotional_image);
            setLoading(false);
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            setLoading(false);
            setAlert(intl.formatMessage(messages.errorLoadImage));
        });
    }
    /**
     * If there is an error
     */
    if (alert) {
        return ((0, jsx_runtime_1.jsx)(material_1.Alert, Object.assign({ color: "error", onClose: () => setAlert(null) }, { children: alert })));
    }
    /**
     * Renders root object (if not hidden by autoHide prop)
     */
    if (!autoHide) {
        return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("input", { type: "file", onChange: handleUpload, ref: fileInput, hidden: true, accept: ".gif,.png,.jpg,.jpeg" }), (0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className), size: "medium", variant: "contained", disabled: loading, onClick: () => fileInput.current.click(), loading: loading }, rest, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "image" }) }))] }));
    }
    return null;
}
exports.default = ChangeGroupCover;
