// a data pool holds frequently played sounds in memory together with decoded audio data to no longer have to decode them from the cache when loaded again
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 { EventBus } from '../event-bus';
import DataPoolItem from './data-pool-item';
import { HTTPLoader } from './loaders/http-loader';
export default class DataPool extends EventBus {
    constructor(context, loader = new HTTPLoader(), maxData = 512) {
        super();
        this.loader = loader;
        this.data = {};
        this.maxData = maxData;
        this.context = context;
    }
    get(path) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.data[path]) {
                return this.data[path].getDecodedData();
            }
            else {
                const buffer = yield this.loader.get(path);
                const decoded = yield this.context.decodeAudioData(buffer);
                const item = new DataPoolItem(path, buffer, decoded);
                const length = Object.keys(this.data).length;
                if (length < this.maxData) {
                    this.data[path] = item;
                }
                else {
                    // TODO: figure out a more clever solution than just removing the first loaded data. Like tracking how much certain data is needed and prioritize them.
                    // const paths: string[] = Object.keys(this.data);
                    // delete this.data[paths[0]];
                    this.data[path] = item;
                }
                return item.getDecodedData();
            }
        });
    }
    clear() {
        this.data = {};
    }
}
