"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chunked_uploady_1 = require("@rpldy/chunked-uploady");
const uploady_1 = require("@rpldy/uploady");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const utils_1 = require("@selfcommunity/utils");
const react_1 = tslib_1.__importStar(require("react"));
const react_intl_1 = require("react-intl");
const Errors_1 = require("../../constants/Errors");
const common_1 = tslib_1.__importDefault(require("../../messages/common"));
const hash_1 = require("../../utils/hash");
exports.default = (props) => {
    // PROPS
    const { type = null, onSuccess = null, onProgress = null, onError = null } = props;
    // REFS
    const firstRender = (0, react_1.useRef)(true);
    const chunkStateRef = react_1.default.useRef({ chunks: {}, setChunk: null, setChunks: null });
    // STATE
    const [chunks, _setChunks] = (0, react_1.useState)({});
    const setChunk = (chunk) => {
        const _chunks = Object.assign(Object.assign({}, chunkStateRef.current.chunks), { [chunk.id]: Object.assign(Object.assign({}, chunkStateRef.current.chunks[chunk.id]), chunk) });
        _setChunks(_chunks);
        chunkStateRef.current.chunks = _chunks;
    };
    const setChunks = (chunks) => {
        _setChunks(chunks);
        chunkStateRef.current.chunks = chunks;
    };
    // Using refs to have the correct chunks values in the callbacks
    // https://stackoverflow.com/questions/57847594/react-hooks-accessing-up-to-date-state-from-within-a-callback
    chunkStateRef.current = { chunks, setChunk, setChunks };
    // CONTEXT
    const scContext = (0, react_core_1.useSCContext)();
    const { refreshSession } = (0, react_core_1.useSCUser)();
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // component update
    (0, react_1.useEffect)(() => {
        if (firstRender.current) {
            firstRender.current = false;
            return;
        }
        onProgress && onProgress(chunks);
    }, [chunks]);
    // LISTENERS
    (0, uploady_1.useItemStartListener)((item) => {
        if (item.file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = (e) => {
                chunkStateRef.current.setChunk({ id: item.id, image: e.target.result });
            };
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            reader.readAsDataURL(item.file);
        }
        chunkStateRef.current.setChunk({ id: item.id, ['upload_id']: null, completed: 0, name: item.file.name });
    });
    (0, uploady_1.useItemProgressListener)((item) => {
        chunkStateRef.current.setChunk({ id: item.id, completed: item.completed });
    });
    (0, chunked_uploady_1.useItemFinishListener)((item) => {
        (0, hash_1.md5)(item.file, 2142880, (hash) => {
            const formData = new FormData();
            formData.append('upload_id', chunkStateRef.current.chunks[item.id].upload_id);
            formData.append('type', chunkStateRef.current.chunks[item.id].type);
            formData.append('md5', hash);
            api_services_1.http
                .request({
                url: api_services_1.Endpoints.ComposerChunkUploadMediaComplete.url(),
                method: api_services_1.Endpoints.ComposerChunkUploadMediaComplete.method,
                data: formData,
                headers: { 'Content-Type': 'multipart/form-data' }
            })
                .then((res) => {
                setTimeout(() => {
                    const _chunks = Object.assign({}, chunkStateRef.current.chunks);
                    delete _chunks[item.id];
                    chunkStateRef.current.setChunks(_chunks);
                    onSuccess(res.data);
                }, 0);
            })
                .catch((error) => {
                console.log(error);
                onError(Object.assign({}, chunkStateRef.current.chunks[item.id]), intl.formatMessage(common_1.default.fileUploadErrorGeneric));
                const _chunks = Object.assign({}, chunkStateRef.current.chunks);
                delete _chunks[item.id];
                chunkStateRef.current.setChunks(_chunks);
            });
        });
    });
    (0, chunked_uploady_1.useItemErrorListener)((item) => {
        onError(Object.assign({}, chunkStateRef.current.chunks[item.id]), intl.formatMessage(common_1.default.fileUploadErrorGeneric));
        const _chunks = Object.assign({}, chunkStateRef.current.chunks);
        delete _chunks[item.id];
        chunkStateRef.current.setChunks(_chunks);
    });
    (0, chunked_uploady_1.useChunkStartListener)((data) => {
        const res = {
            url: `${scContext.settings.portal}${api_services_1.Endpoints.ComposerChunkUploadMedia.url()}`,
            sendOptions: {
                paramName: 'image',
                method: api_services_1.Endpoints.ComposerChunkUploadMedia.method,
                formatServerResponse: (response, status, _headers) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
                    if (status === 401) {
                        yield refreshSession();
                    }
                    return Promise.resolve(JSON.parse(response));
                })
            }
        };
        if (chunkStateRef.current.chunks[data.item.id].upload_id) {
            res.sendOptions.params = { ['upload_id']: chunkStateRef.current.chunks[data.item.id].upload_id };
        }
        else {
            chunkStateRef.current.setChunk({ id: data.item.id, type: type || data.sendOptions.paramName });
        }
        return res;
    });
    (0, chunked_uploady_1.useChunkFinishListener)((data) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        const _data = yield data.uploadData.response.data;
        chunkStateRef.current.setChunk({ id: data.item.id, ['upload_id']: _data.upload_id });
    }));
    (0, chunked_uploady_1.useRequestPreSend)(({ items, options }) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        const destination = ['JWT', 'OAuth'].includes(scContext.settings.session.type)
            ? {
                headers: { Authorization: `Bearer ${scContext.settings.session.authToken.accessToken}` }
            }
            : {};
        if (items.length == 0) {
            return Promise.resolve({ options, destination });
        }
        //returned object can be wrapped with a promise
        return new Promise((resolve) => {
            Promise.all(items.map((item) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
                return Object.assign(Object.assign({}, item), { file: item.file.type.startsWith('image/') && item.file.type !== 'image/gif' ? yield (0, utils_1.resizeImage)(item.file) : item.file });
            })))
                .then((items) => {
                resolve({
                    items: items,
                    options: {
                        inputFieldName: options.inputFieldName,
                        destination
                    }
                });
            })
                .catch((error) => {
                utils_1.Logger.error(error, Errors_1.SCOPE_SC_UI);
                resolve({
                    options: {
                        inputFieldName: options.inputFieldName,
                        destination
                    }
                });
            });
        });
    }));
    return null;
};
