import sleep from "@insite/client-framework/Common/Sleep";
import { rawRequest } from "@insite/client-framework/Services/ApiService";
import { exportContent as apiExportContent } from "@insite/shell/Services/ContentAdminService";
import {
    checkImportContentStatus,
    importContent as apiImportContent,
    restoreContent as apiRestoreContent,
} from "@insite/shell/Services/WebsitesService";
import { ImportExportModalState } from "@insite/shell/Store/ImportExportModal/ImportExportModalState";
import { AnyShellAction } from "@insite/shell/Store/Reducers";
import ShellThunkAction from "@insite/shell/Store/ShellThunkAction";

export const showImportExportModal = (): AnyShellAction => ({
    type: "ImportExportModal/SetShowModal",
    showModal: true,
});

export const closeImportExportModal = (): AnyShellAction => ({
    type: "ImportExportModal/SetShowModal",
    showModal: false,
});

export const showRestoreContentModal = (): AnyShellAction => ({
    type: "RestoreContentModal/SetShowModal",
    showRestoreModal: true,
});

export const closeRestoreContentModal = (): AnyShellAction => ({
    type: "RestoreContentModal/SetShowModal",
    showRestoreModal: false,
});

export const setTask = (task: ImportExportModalState["task"]): AnyShellAction => ({
    type: "ImportExportModal/SetTask",
    task,
});

export const setOnlyExportPublishedContent = (value: boolean): AnyShellAction => ({
    type: "ImportExportModal/SetOnlyExportPublishedContent",
    value,
});

export const setRestoreInitialPages = (value: boolean): AnyShellAction => ({
    type: "ImportExportModal/SetRestoreInitialPages",
    value,
});

export const exportContent = (): ShellThunkAction => async (dispatch, getState) => {
    dispatch({
        type: "ImportExportModal/BeginTask",
    });

    const onlyPublished = getState().importExportModal.onlyExportPublishedContent;
    const filePath = await apiExportContent(onlyPublished);
    const fileResponse = await rawRequest(
        `/api/v1/admin/systemFiles/content?path=${encodeURIComponent(filePath)}&useJwtToken=true`,
        "POST",
    );
    const fileBlob = await fileResponse.blob();
    const fileObjectUrl = window.URL.createObjectURL(fileBlob);
    const hiddenA = document.createElement("a");
    hiddenA.style.display = "none";
    hiddenA.href = fileObjectUrl;
    hiddenA.download = filePath.split("\\").pop() || "";
    document.body.appendChild(hiddenA);
    hiddenA.click();
    window.URL.revokeObjectURL(fileObjectUrl);
    hiddenA.parentNode?.removeChild(hiddenA);

    dispatch({
        type: "ImportExportModal/SetShowModal",
        showModal: false,
    });
};

export const importContent =
    (file: File, restoreInitialPages?: boolean): ShellThunkAction =>
    async (dispatch, getState) => {
        dispatch({
            type: "ImportExportModal/BeginTask",
        });

        const { success, errorMessage, jobId } = await apiImportContent(file);
        if (!success) {
            dispatch({
                type: "ImportExportModal/SetErrorMessage",
                errorMessage,
            });

            return;
        }

        const i = setInterval(async () => {
            const { isFinished, errorMessage } = await checkImportContentStatus(jobId);
            if (isFinished) {
                clearInterval(i);
                if (errorMessage) {
                    dispatch({
                        type: "ImportExportModal/SetErrorMessage",
                        errorMessage,
                    });
                } else {
                    window.location.href = `/ContentAdmin/Page${
                        restoreInitialPages ? "?restoreInitialPages=true" : ""
                    }`;
                }
            }
        }, 3000);
    };

export const confirmImport = (): AnyShellAction => ({
    type: "ImportExportModal/ConfirmImport",
});

export const restoreContent = (): ShellThunkAction => async dispatch => {
    dispatch({
        type: "RestoreContentModal/BeginTask",
    });

    const start = Date.now();
    const { success, errorMessage } = await apiRestoreContent();
    const seconds = Math.floor((Date.now() - start) / 1e3);

    if (success) {
        // DefaultCheckMemoryCacheTimerIntervalInMilliseconds -> 10
        const sleepTime = Math.max(0, 5 - seconds);
        if (sleepTime) {
            await sleep(sleepTime * 1e3);
        }
        window.location.href = "/ContentAdmin/Page";
    } else {
        dispatch({
            type: "ImportExportModal/SetErrorMessage",
            errorMessage,
        });
    }
};
