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 { URI } from '../../../base/common/uri.js';
import { Schemas } from '../../../base/common/network.js';
import { basename, extname } from '../../../base/common/path.js';
export class HTMLFileSystemProvider {
    //#endregion
    constructor(indexedDB, store, logService) {
        this.indexedDB = indexedDB;
        this.store = store;
        this.logService = logService;
        //#endregion
        //#region File/Directoy Handle Registry
        this._files = new Map();
        this._directories = new Map();
    }
    registerFileHandle(handle) {
        return this.registerHandle(handle, this._files);
    }
    registerDirectoryHandle(handle) {
        return this.registerHandle(handle, this._directories);
    }
    registerHandle(handle, map) {
        var _a, _b, _c;
        return __awaiter(this, void 0, void 0, function* () {
            let handleId = `/${handle.name}`;
            // Compute a valid handle ID in case this exists already
            if (map.has(handleId) && !(yield ((_a = map.get(handleId)) === null || _a === void 0 ? void 0 : _a.isSameEntry(handle)))) {
                const fileExt = extname(handle.name);
                const fileName = basename(handle.name, fileExt);
                let handleIdCounter = 1;
                do {
                    handleId = `/${fileName}-${handleIdCounter++}${fileExt}`;
                } while (map.has(handleId) && !(yield ((_b = map.get(handleId)) === null || _b === void 0 ? void 0 : _b.isSameEntry(handle))));
            }
            map.set(handleId, handle);
            // Remember in IndexDB for future lookup
            try {
                yield ((_c = this.indexedDB) === null || _c === void 0 ? void 0 : _c.runInTransaction(this.store, 'readwrite', objectStore => objectStore.put(handle, handleId)));
            }
            catch (error) {
                this.logService.error(error);
            }
            return URI.from({ scheme: Schemas.file, path: handleId });
        });
    }
}
