import { AssetLoader } from "./AssetLoader.js";
import { Asset } from "../Asset.js";

export class SoundAssetLoader extends AssetLoader {
    /**
     *
     * @param {AudioContext} context
     */
    constructor(context) {
        super();

        /**
         *
         * @type {AudioContext}
         */
        this.audioContext = context;
    }

    load(scope, path, success, failure, progress) {
        // Load a sound file using an ArrayBuffer XMLHttpRequest.
        const request = new XMLHttpRequest();

        request.open("GET", path, true);

        request.responseType = "arraybuffer";

        const context = this.audioContext;

        request.onload = function (e) {
            //decode works asynchronously, this is important to prevent lag in main thread
            context.decodeAudioData(request.response, function (buffer) {
                const byteSize = e.total;

                const asset = new Asset(() => buffer, byteSize);

                success(asset);
            }, failure);
        };

        request.onerror = failure;

        request.onprogress = function (e) {
            //report progress
            progress(e.loaded, e.total);
        };

        request.send();
    }
}
