"use strict";

import { readFileSync, writeFileSync } from "fs";

export class User {
    /**
     * 
     * @param {String} login 
     * @param {String} password 
     * @param {String} status 
     */
    constructor(login, password, status) {
        this.login = login;
        this.password = password;
        this.status = status;
    }
}

export class UserDB {
    /** @type {Map.<String, User>} */
    users = new Map();

    constructor() {
        this.#loadData();
    }

    #loadData() {
        try {
            const fileData = readFileSync("users.json", "utf-8");
            const usersData = JSON.parse(fileData);
            usersData.forEach(user => {
                this.users.set(
                    user["login"],
                    new User(user["login"], user["password"], user["status"])
                );
            });
        } catch (_) { }
    }

    saveData() {
        const data = JSON.stringify(Array.from(this.users.keys()).map(k => {
            const user = this.users.get(k);
            return {
                login: user.login,
                password: user.password,
                status: user.status
            };
        }));
        writeFileSync("./users.json", data, { encoding: "utf-8", flag: "w+" });
    }

    /**
     * 
     * @param {User} login 
     * @returns Exists user in DB or not
     */
    hasUser(login) {
        return this.users.has(login);
    }

    /**
     * 
     * @param {User} user 
     */
    putUser(user) {
        if (this.hasUser(user.login)) {
            throw new Error(`User ${user.login} exists!`);
        }

        this.users.set(user.login, user);
        this.saveData();
    }

    /**
     * 
     * @param {String} login 
     * @returns User object
     */
    getUser(login) {
        return this.users.get(login);
    }

    /**
     * 
     * @returns Users count
     */
    getUsersCount() {
        return this.users.size;
    }
}