import { assert } from "../../../../core/assert.js";
import { noop } from "../../../../core/function/noop.js";
import { GameAssetType } from "../../../asset/GameAssetType.js";
import { SoundTrackFlags } from "./SoundTrackFlags.js";

/**
 * @param {SoundTrack} track
 * @param {AssetManager} assetManager
 * @param {function(Asset<AudioBuffer>)} [resolve]
 * @param {function} [reject]
 */
export function loadSoundTrackAsset(track, assetManager, resolve = noop, reject = noop) {
    assert.defined(track, 'track');
    assert.defined(assetManager, 'assetManager');

    assert.isFunction(resolve, 'resolve');
    assert.isFunction(reject, 'reject');

    const track_url = track.url;

    let asset_path;

    if (track.getFlag(SoundTrackFlags.UsingAliasURL)) {
        const assetDescription = assetManager.resolveAlias(track_url);

        if (assetDescription === undefined) {

            console.warn(`Asset alias '${track_url}' not found`);

            asset_path = `# MISSING_ALIAS (${track_url})`;

        } else {
            asset_path = assetDescription.path;
        }

    } else {
        asset_path = track_url;
    }

    assetManager.get({ path: asset_path, type: GameAssetType.Sound, callback: resolve, failure: reject });
}
