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 { DEFAULT_DOMAIN } from './constants';
const loadExternalApi = (domain, release, appId) => __awaiter(void 0, void 0, void 0, function* () {
    return new Promise((resolve, reject) => {
        if (window.JitsiMeetExternalAPI) {
            return resolve(window.JitsiMeetExternalAPI);
        }
        const script = document.createElement('script');
        const releaseParam = release ? `?release=${release}` : '';
        const appIdPath = appId ? `${appId}/` : '';
        script.async = true;
        script.src = `https://${domain}/${appIdPath}external_api.js${releaseParam}`;
        script.onload = () => resolve(window.JitsiMeetExternalAPI);
        script.onerror = () => reject(new Error(`Script load error: ${script.src}`));
        document.head.appendChild(script);
    });
});
let scriptPromise;
/**
 * Injects the external_api.js script for the corresponding domain in DOM
 * and resolves with either the `JitsiMeetExternalApi` class definition or an error.
 *
 * Only the first script will be injected, therefore avoid using multiple instances
 * with mixed domains and release version at the same time.
 *
 * @param {string} domain - The domain of the external API
 * @param {string} release - The Jitsi Meet release. Expected format: 'release-1234'
 * @param {string} appId - The tenant for JaaS Meetings
 * @returns {Promise<JitsiMeetExternalApi>} - The JitsiMeetExternalAPI or an error
 */
export const fetchExternalApi = (domain = DEFAULT_DOMAIN, release, appId) => {
    if (scriptPromise) {
        return scriptPromise;
    }
    scriptPromise = loadExternalApi(domain, release, appId);
    return scriptPromise;
};
