import { useEffect, useState } from "react";
import { FEAGlobals } from "../../common/Globals";
/**
 * When we close this window, if the user isn't logged in then it must mean we
 * were using OAuth to log in, and it failed, so shut down the entire app. Otherwise
 * we were just using it to authenticate a client, in which case we just want to close
 * this window but keep Finsemble running.
 */
const cancel = () => {
    FEAGlobals.FSBL.Clients.AuthenticationClient.getCurrentCredentials((err, credentials) => {
        if (!err && !credentials) {
            FEAGlobals.FSBL.shutdownApplication();
        }
        else {
            FEAGlobals.FSBL.Clients.WindowClient.close();
        }
    });
};
/**
 * This is called when the OAuth transaction was successful. If this is being used for startup then
 * Finsemble is given the go-ahead and provided credentials. If a business logic handler has been
 * provided to the hook it will be run before Finsemble proceeds. Finally, the window itself is closed.
 */
const success = async (setError, handler) => {
    const { err, data } = await FEAGlobals.FSBL.Clients.AuthenticationClient.completeOAUTH(null, null);
    if (err) {
        // This updates React state, so that the hook's callee will update with a fresh error
        setError(err.toString());
        return;
    }
    window.authCompleted = true;
    const credentials = data;
    const finish = () => {
        // In the special case of "startup" then we publish the authorization, which releases Finsemble and lets it start
        if (credentials.config.name === "startup") {
            // "sub" is the user ID provided by the OP. Not all OP's support this. If not supported, then we just set the user to the access token.
            const user = credentials.sub || credentials.access_token || credentials.code;
            // Finish the authentication process
            FEAGlobals.FSBL.Clients.RouterClient.transmit("AuthenticationService.authorization", {
                user: user,
                credentials: credentials,
            });
        }
        FEAGlobals.FSBL.Clients.WindowClient.close();
    };
    if (handler) {
        handler(credentials, () => {
            finish();
        });
    }
    else {
        finish();
    }
};
/**
 *  If SDD mode is enabled then this window must be from test auth, so we report back and close it
 */
const sendTestResponse = (err) => {
    FEAGlobals.FSBL.Clients.RouterClient.transmit("SDD-Auth-Test-Response", { err });
    FEAGlobals.FSBL.Clients.WindowClient.close();
};
/**
 * Oauth servers will set error_description to the text of any error.
 * URLSearchParams will automatically decode that response.
 */
const lookForErrorInQueryString = () => {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get("error_description");
};
/**
 * Processes the Oauth response. If there's an error then it will be displayed,
 * otherwise oauth transaction will complete and the window will be closed.
 */
const processResponse = async (setError, handler) => {
    FEAGlobals.FSBL.getFSBLInfo().then(({ sddEnabled }) => {
        const error = lookForErrorInQueryString();
        if (error) {
            if (sddEnabled)
                sendTestResponse(error);
            setError(error);
            return;
        }
        // store on Window so preloads/authentication has access to this info
        window.authCompleted = false;
        if (sddEnabled) {
            sendTestResponse(null);
        }
        else {
            success(setError, handler);
        }
    });
};
/**
 * A hook that can be used in an OAuth response page. This will process the identity provider's response
 * which should be in the page's query string. If successful then Finsemble will be provided with the
 * returned credentials and the page will be closed. If unsuccessful, then the error will be returned from
 * the hook. The hook returns a cancel() function which can be used to discontinue upon an error.
 *
 * @param handler An optional handler which can run business logic on a successful OAuth transaction. This will
 * run before the window closes. The first parameter will be the OAuth credentials. The second parameter is a
 * callback function which must be run to close the OAuth response window.
 */
export const useOAuth = (handler) => {
    const [error, setError] = useState("");
    // Process the response (by examining the query string)
    // Since this is asynchronous, we pass the setError() state dispatcher
    // This only happens once
    useEffect(() => {
        processResponse(setError, handler);
    }, []);
    return {
        error,
        cancel,
    };
};
//# sourceMappingURL=useOAuth.js.map