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 { Downloader } from './downloader';
import { Queue } from './queue';
import { Manifest } from './manifest';
import { AssetStorage } from './storage';
import { EventBus } from '../event-bus';
import { buildPath } from './utils';
export class AssetManager extends EventBus {
    constructor(name, basePath) {
        super();
        this.name = name;
        this.basePath = basePath;
        this.queue = new Queue();
        this.storage = new AssetStorage(name);
        this.downloader = new Downloader(this.storage, this.queue, this.basePath);
        console.log(`Asset manager initialized`);
    }
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.storage.init();
            return true;
        });
    }
    setManifest(path) {
        return __awaiter(this, void 0, void 0, function* () {
            this.manifest = yield Manifest(`${this.basePath}/${path}`);
            this.storage.setManifest(this.manifest);
            return this.manifest;
        });
    }
    enqueue(path) {
        this.queue.add(path);
    }
    download() {
        return __awaiter(this, void 0, void 0, function* () {
            const result = yield this.downloader.download();
            return result;
        });
    }
    downloadFromManifest(key) {
        return __awaiter(this, void 0, void 0, function* () {
            const paths = this.manifest[key];
            paths.forEach((path) => this.enqueue(path));
            this.downloader.subscribe('download.progress', (info) => this.emit('progress', info));
            const files = yield this.downloader.download();
            this.downloader.unsubscribeAll('download.progress');
            return files;
        });
    }
    downloadFile(path) {
        return __awaiter(this, void 0, void 0, function* () {
            const result = yield this.downloader.downloadItem(buildPath(this.basePath, path));
            return result;
        });
    }
    setBasePath(path) {
        this.basePath = path;
        this.downloader.setBasePath(this.basePath);
    }
    clearCache() {
        this.storage.clear();
    }
}
