"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
class Passwords {
    static async load(dir, onMiss) {
        this.saveFile = (0, node_path_1.join)(dir, 'credentials.json');
        this.resolve = onMiss;
        this.store = new Map(JSON.parse((await (0, promises_1.readFile)(this.saveFile)).toString()).map(([id, password]) => [id, [password, true]]));
    }
    static set(id, password, remember = false) {
        if (password === false) {
            this.pending.get(id)?.[1]();
        }
        else {
            this.pending.get(id)?.[0](password);
            remember && this.store.set(id, [password, false]);
        }
    }
    static save(id, password) {
        this.store.set(id, [password, true]);
        this.dump();
    }
    static async get(id, skipMissing = false) {
        if (this.store.has(id)) {
            return this.store.get(id)[0];
        }
        if (skipMissing) {
            return '';
        }
        const p = new Promise((resolve, reject) => this.pending.set(id, [resolve, reject]));
        this.resolve(id);
        return p;
    }
    static delete(id, saved) {
        const found = this.store.get(id);
        if (found && found[1] == saved) {
            this.store.delete(id);
            found[1] == true && this.dump();
        }
        this.pending.delete(id);
    }
    static dump() {
        (0, promises_1.writeFile)(this.saveFile, JSON.stringify(Array.from(this.store.entries())
            .filter(([, [, save]]) => save)
            .map(([id, [password,]]) => [id, password])));
    }
}
Passwords.saveFile = '';
Passwords.pending = new Map();
exports.default = Passwords;
