/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import { readFileSync, writeFileSync } from "fs";
import { app } from "electron";
import { join } from "path";

const directory = app.getPath("userData");
const filename = "config.json";
const filePath = join(directory, filename);
class JSONStorage {
  static get<T>(key: string, def?: T): T {
    const json = this.readJson();
    return json[key] === undefined ? def : json[key];
  }

  static set(key: string, value: unknown) {
    const json = this.readJson();
    json[key] = value;
    this.writeJson(json);
  }

  static clear() {
    this.writeJson({});
  }

  private static readJson() {
    try {
      const json = readFileSync(filePath, "utf-8");
      return JSON.parse(json);
    } catch (e) {
      console.error(e);
      return {};
    }
  }

  private static writeJson(json: Record<string, unknown>) {
    try {
      writeFileSync(filePath, JSON.stringify(json));
    } catch (e) {
      console.error(e);
    }
  }
}
export { JSONStorage };
