/**
 * Loads a script by injecting it into the head. Returns a
 * promise which resolves on the `onload` event of the script.
 *
 * @param {string} src - URL to load the script from.
 * @param {string} id - ID which is applied to the script tag.
 * @returns {Promise}
 */
export function loadScript (src, id) {
    return new Promise((resolve, reject) => {
        if (!src || !id) {
            reject('Please specify script src and id');
        }

        const existingScript = document.getElementById(id);
        if (!existingScript) {
            const script = document.createElement('script');
            script.src = src;
            script.id = id;
            document.body.appendChild(script);
            script.onload = () => resolve(true);
        } else {
            existingScript.onload = () => resolve(true);
        }
    });
}

/**
 * @param {string} src
 * @param {string} id
 * @returns {Promise}
 */
export function loadStyle(src, id) {
    return new Promise((resolve, reject) => {
        if (!src || !id) {
            reject('Please specify script src and id');
        }

        const existingStyle = document.getElementById(id);
        if (!existingStyle) {
            const style = document.createElement('link');
            style.rel = 'stylesheet';
            style.type = 'text/css';
            style.href = src;
            style.id = id;
            document.body.appendChild(style);
            style.onload = () => resolve(true);
        } else {
            existingStyle.onload = () => resolve(true);
        }
    });
}

/**
 * @param {string} id
 * @returns {*}
 */
export function getLoadingPromise(id) {
    window._loadingPromises = window._loadingPromises || {};
    return window._loadingPromises[id];
}

/**
 * @param {string} id
 * @param {Function} getter
 * @returns {*}
 */
export function ensureLoadingPromiseOnlyExistsOnce(id, getter) {
    const loadingPromise = getLoadingPromise(id);

    if (loadingPromise) {
        return loadingPromise;
    }

    window._loadingPromises[id] = getter();
    return window._loadingPromises[id];
}
