import * as path from 'path'

import * as low from 'lowdb'
import * as FileSync from 'lowdb/adapters/FileAsync'

import { STORAGE_DIR } from '../config/foundation'

const adapter = new FileSync(path.join(STORAGE_DIR, 'db.json'))

function mixin(db) {
  db._.mixin({
    updateOrAdd: function(arr, obj, key) {
      const existed = db._.find(arr, x => x[key] === obj[key])
      if(existed) {
        Object.assign(existed, obj);
      } else {
        arr.push(obj);
      }
      return arr
    }
  })
}

export var db

export async function initDB() {
  db = await low(adapter)
  mixin(db)
  await db.defaults({
    component: [],
    project: [],
    statistics: [],
    template: []
  })
    .write()
}


