import path from 'path';
import { appPath } from '../../core/app-path';
import fs from 'fs-extra';

export const enum StoreKeys {
  'COOKIES' = 'cookies',
}

type Store = {
  [key in StoreKeys]?: any;
};

interface IStoreOptions {
  path: string;
}

let store: Store = {};
let synced = false;

const options: IStoreOptions = {
  path: path.resolve(appPath, 'store', 'store.json'),
};
const folder = path.dirname(options.path);

function initDir(): Promise<void> {
  if (!fs.existsSync(folder)) {
    return fs.promises.mkdir(folder, { recursive: true }).then(() => writeUnsave());
  }
  if (!fs.existsSync(options.path)) {
    return writeUnsave();
  }
  return Promise.resolve();
}

function writeUnsave(): Promise<void> {
  return fs.writeFile(options.path, JSON.stringify(store));
}

function read(): Promise<void> {
  return initDir().then(() =>
    fs.readFile(options.path).then((buf: Buffer) => {
      store = JSON.parse(buf.toString());
      synced = true;
    })
  );
}

function write(): Promise<void> {
  return initDir().then(() =>
    writeUnsave().then(() => {
      synced = false;
    })
  );
}

export function load(key: StoreKeys): Promise<any> {
  if (synced) {
    return Promise.resolve(store[key]);
  }
  return read().then(() => Promise.resolve(store[key]));
}

export function save(key: StoreKeys, data: any): Promise<void> {
  store[key] = data;
  return write();
}
