// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { failureStates, successStates, } from "./models";
import { isUnexpectedPollingResponse } from "./requestUtils";
function isPollingDone(rawResponse) {
    var _a;
    if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) {
        return false;
    }
    const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
    const state = typeof status === "string" ? status.toLowerCase() : "succeeded";
    if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) {
        throw new Error(`The long running operation has failed. The provisioning state: ${state}.`);
    }
    return successStates.includes(state);
}
/**
 * Sends a request to the URI of the provisioned resource if needed.
 */
async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) {
    switch (lroResourceLocationConfig) {
        case "original-uri":
            return lro.sendPollRequest(lro.requestPath);
        case "azure-async-operation":
            return undefined;
        case "location":
        default:
            return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath);
    }
}
export function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) {
    return (response) => {
        if (isPollingDone(response.rawResponse)) {
            if (resourceLocation === undefined) {
                return Object.assign(Object.assign({}, response), { done: true });
            }
            else {
                return Object.assign(Object.assign({}, response), { done: false, next: async () => {
                        const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig);
                        return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true });
                    } });
            }
        }
        return Object.assign(Object.assign({}, response), { done: false });
    };
}
//# sourceMappingURL=locationPolling.js.map