"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 system_1 = require("@mui/system");
const styles_1 = require("@mui/material/styles");
const material_1 = require("@mui/material");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const lab_1 = require("@mui/lab");
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const react_core_1 = require("@selfcommunity/react-core");
const Errors_1 = require("../../constants/Errors");
const react_intl_1 = require("react-intl");
const date_fns_1 = require("date-fns");
const PREFIX = 'SCAccountDataPortability';
const classes = {
    root: `${PREFIX}-root`,
    createButton: `${PREFIX}-create-button`,
    downloadButton: `${PREFIX}-download-button`,
    generationInfo: `${PREFIX}-generation-info`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
/**
 * > API documentation for the Community-JS AccountDataPortability component. Learn about the available props and the CSS API.
 *
 *
 * This component allows users to display the logic behind data portability of user data.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/AccountDataPortability)

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

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCAccountDataPortability-root|Styles applied to the root element.|
 |createButton|.SCAccountDataPortability-create-button|Styles applied to the create data portability button in the rejection section.|
 |downloadButton|.SCAccountDataPortability-download-button|Styles applied to the download data portability button in the rejection section.|
 |generationInfo|.SCAccountDataPortability-generation-info|Styles applied to the section with generation information.|

 * @param inProps
 */
function AccountDataPortability(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className } = props, rest = tslib_1.__rest(props, ["className"]);
    // CONTEXT
    const scUserContext = (0, react_1.useContext)(react_core_1.SCUserContext);
    // STATE
    const [dataPortability, setDataPortability] = (0, react_1.useState)(null);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const [downloadingDataPortability, setDownloadingDataPortability] = (0, react_1.useState)(false);
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    /**
     * Handle create data portability
     */
    const handleCreateDataPortabilityFile = () => {
        setLoading(true);
        api_services_1.DataPortabilityService.generateDataPortability()
            .then((res) => {
            if (res) {
                setDataPortability(dataPortability);
            }
        })
            .catch((_error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, _error);
        })
            .then(() => setLoading(false));
    };
    /**
     * Handle download data portability
     */
    const handleDownloadDataPortabilityFile = () => {
        setDownloadingDataPortability(true);
        api_services_1.DataPortabilityService.downloadDataPortability({ timeout: 30 * 60 * 1000 })
            .then((res) => {
            const url = window.URL.createObjectURL(new Blob([res], { type: 'application/zip' }));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `${scUserContext.user.username}_${intl.formatDate((0, date_fns_1.format)(new Date(), "yyyy-MM-dd'T'HH:mm:ssxxx"), {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric'
            })}.zip`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            setDownloadingDataPortability(false);
        })
            .catch((_error) => {
            setDownloadingDataPortability(false);
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, _error);
        });
    };
    /**
     * Fetch data portability status
     */
    const fetchDataPortabilityStatus = () => {
        api_services_1.DataPortabilityService.dataPortabilityStatus()
            .then((res) => {
            if (res) {
                if (!res.computing && res.generated_at) {
                    setLoading(false);
                }
                setDataPortability(res);
            }
        })
            .catch((_error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, _error);
        })
            .then(() => setLoading(false));
    };
    /**
     * Sync data portability status
     */
    (0, react_1.useEffect)(() => {
        // TODO: ?????
        let interval;
        if (authUserId !== null) {
            fetchDataPortabilityStatus();
            interval = setInterval(() => {
                fetchDataPortabilityStatus();
            }, 5000);
        }
        return () => interval && clearInterval(interval);
    }, [authUserId]);
    /**
     * If there's no authUserId, component is hidden.
     */
    if (!authUserId) {
        return null;
    }
    /**
     * Renders root object
     */
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h6" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.accountDataPortability.title", defaultMessage: "ui.accountDataPortability.title", values: { username: (0, utils_1.capitalize)(scUserContext.user.username) } }) })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body2", component: "div" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.accountDataPortability.info", defaultMessage: "ui.accountDataPortability.info", values: {
                        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                        // @ts-ignore
                        li: (chunks) => (0, jsx_runtime_1.jsx)("li", { children: chunks }),
                        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                        // @ts-ignore
                        ul: (chunks) => (0, jsx_runtime_1.jsx)("ul", { children: chunks })
                    } }) })), (0, jsx_runtime_1.jsx)(lab_1.LoadingButton, Object.assign({ size: "small", loading: (dataPortability && dataPortability.computing) || loading, disabled: !dataPortability ||
                    (dataPortability &&
                        (dataPortability.computing ||
                            (dataPortability.requested_at && (0, date_fns_1.differenceInHours)(new Date(), (0, date_fns_1.parseISO)(dataPortability.requested_at.toString())) < 24))), loadingPosition: "start", startIcon: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "folder_open" }), variant: "outlined", className: classes.createButton, onClick: handleCreateDataPortabilityFile }, { children: (dataPortability && dataPortability.computing) || loading ? ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.accountDataPortability.createLoadingButton", defaultMessage: "ui.accountDataPortability.createLoadingButton" })) : ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.accountDataPortability.createButton", defaultMessage: "ui.accountDataPortability.createButton" })) })), dataPortability && !dataPortability.computing && dataPortability.generated_at && ((0, jsx_runtime_1.jsx)(lab_1.LoadingButton, Object.assign({ size: "small", loading: downloadingDataPortability, loadingPosition: "start", startIcon: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "cloud_download_outlined" }), variant: 'outlined', className: classes.downloadButton, onClick: handleDownloadDataPortabilityFile }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.accountDataPortability.downloadButton", defaultMessage: "ui.accountDataPortability.downloadButton" }) }))), (0, jsx_runtime_1.jsx)("br", {}), dataPortability && !dataPortability.computing && dataPortability.generated_at && ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.generationInfo, variant: "body2" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.accountDataPortability.generatedInfo", defaultMessage: "ui.accountDataPortability.generatedInfo", values: {
                        date: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedDate, { value: dataPortability.requested_at, day: "numeric", month: "long", year: "numeric" }),
                        time: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedTime, { value: dataPortability.requested_at })
                    } }) })))] })));
}
exports.default = AccountDataPortability;
