import { cloneObject } from "../util";
import { deepEqual } from "../objects/deepEqual";
import { getSchedulerApiUrl } from "./_internal/internalContentUtils";
// Any code referencing these functions must first pass isDownloadSchedulingAvailable
/**
 * Get the schedule for an item. If no schedule is found, returns null.
 * @param itemId The item to get the schedule for
 * @param requestOptions The request options needed to get the HubApiUrl
 * @returns The schedule for the item OR null if no schedule is set
 */
export const getSchedule = async (itemId, requestOptions) => {
    const fetchResponse = await fetch(getSchedulerApiUrl(itemId, requestOptions));
    const schedule = await fetchResponse.json();
    if (!fetchResponse.ok || schedule.statusCode === 404) {
        return {
            message: `Download schedule not found for item ${itemId}`,
            statusCode: 404,
            schedule: null,
        };
    }
    // if the schedule mode is set to manual, return it
    if (schedule.mode === "manual") {
        return {
            schedule: {
                mode: "manual",
            },
            message: `Download schedule found for item ${itemId}`,
            statusCode: 200,
        };
    }
    // if the schedule is set, return it with added mode
    delete schedule.itemId;
    switch (schedule.cadence) {
        case "daily":
        case "weekly":
        case "monthly":
        case "yearly":
            return {
                schedule: Object.assign(Object.assign({}, schedule), { mode: "scheduled" }),
                message: `Download schedule found for item ${itemId}`,
                statusCode: 200,
            };
    }
};
/**
 * Set the schedule for an item
 * @param itemId The item to set the schedule for
 * @param schedule The schedule to set
 * @param requestOptions The request options needed to get the HubApiUrl
 */
export const setSchedule = async (itemId, schedule, requestOptions) => {
    const body = cloneObject(schedule);
    if (body.mode !== "manual") {
        // remove mode if not manual
        delete body.mode;
    }
    const url = getSchedulerApiUrl(itemId, requestOptions);
    const options = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            accept: "application/json",
        },
        body: JSON.stringify(Object.assign(Object.assign({}, body), { itemId })),
    };
    const response = await fetch(url, options);
    return Object.assign(Object.assign({}, (await response.json())), { statusCode: response.status });
};
/**
 * Delete the schedule for an item
 * @param itemId The item to delete the schedule for
 * @param requestOptions The request options needed to get the HubApiUrl
 */
export const deleteSchedule = async (itemId, requestOptions) => {
    const url = getSchedulerApiUrl(itemId, requestOptions);
    const options = {
        method: "DELETE",
        headers: {
            accept: "application/json",
        },
    };
    const response = await fetch(url, options);
    return Object.assign(Object.assign({}, (await response.json())), { statusCode: response.status });
};
/**
 * Checks if the content schedule should be updated and updates it if necessary
 * @param content The content to check and update the schedule for (should include any new schedule information)
 * @param requestOptions The request options needed to get the HubApiUrl
 */
export const maybeUpdateSchedule = async (content, requestOptions) => {
    const scheduleResponse = await getSchedule(content.id, requestOptions);
    // if no schedule is set and incoming schedule is automatic, do nothing
    if (content.schedule.mode === "automatic" &&
        scheduleResponse.statusCode === 404) {
        return {
            message: "No schedule set, and incoming schedule is automatic.",
            statusCode: 404,
        };
    }
    if (!deepEqual(content.schedule, scheduleResponse.schedule)) {
        // if current and incoming schedules differ
        if (content.schedule.mode === "automatic") {
            // and incoming schedule is automatic
            return await deleteSchedule(content.id, requestOptions); // delete the schedule
        }
        else {
            // else
            return await setSchedule(content.id, content.schedule, requestOptions); // set the schedule
        }
    }
    return { message: "No action needed as schedules deepEqual each other." };
};
/**
 * To be used before calling any of the schedule functions in order to prevent fetch
 * requests to scheduler API from portal/enterprise
 *
 * Note: After a discussion w/ Dave, we decided this check is preferred to passing the context
 * into functions that would need checkPermission
 * @param requestOptions The request options needed to get the HubApiUrl
 * @returns Whether or not the scheduling feature is available
 */
export const isDownloadSchedulingAvailable = (requestOptions, access) => {
    var _a, _b;
    const token = (_a = requestOptions.authentication) === null || _a === void 0 ? void 0 : _a.token;
    return (((_b = requestOptions.portal) === null || _b === void 0 ? void 0 : _b.includes("arcgis.com")) &&
        access === "public" &&
        !!token);
};
//# sourceMappingURL=manageSchedule.js.map