var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { AuthUtils } from '@dndbeyond/authentication-lib-js';
import { isValidGameId } from '@dndbeyond/message-broker-lib';
import { useEffect, useMemo } from 'react';
import { useAwaitMessageBroker } from '../useAwaitMessageBroker';
export const useActiveCharacters = (authUrl, baseUrl, callback) => {
    const mb = useAwaitMessageBroker();
    const getShortTermToken = useMemo(() => AuthUtils.makeGetShortTermToken({ authUrl }), [authUrl]);
    useEffect(() => {
        if (process.env.NODE_ENV === 'test' ||
            !(mb && mb.gameId && isValidGameId(mb.gameId))) {
            return;
        }
        const controller = new AbortController();
        const { signal } = controller;
        (() => __awaiter(void 0, void 0, void 0, function* () {
            let stt = undefined;
            let response = undefined;
            let data = undefined;
            try {
                stt = yield getShortTermToken();
            }
            catch (error) {
                console.error('Failed to get stt', error);
                return;
            }
            try {
                response = yield fetch(`${baseUrl}/campaigns/v1/${mb.gameId}/characters`, {
                    signal,
                    headers: {
                        Authorization: `Bearer ${stt}`,
                    },
                });
            }
            catch (error) {
                console.error('Failed to fetch', error);
                return;
            }
            try {
                ({ data } = yield response.json());
            }
            catch (error) {
                console.error('Failed to parse json', error);
                return;
            }
            if (!signal.aborted && data !== undefined) {
                callback(data);
            }
        }))();
        return () => {
            controller.abort();
        };
    }, [baseUrl, callback, getShortTermToken, mb, mb === null || mb === void 0 ? void 0 : mb.gameId]);
};
//# sourceMappingURL=useActiveCharacters.js.map