import Util from './util.mjs'
import getLog from './log.mjs'
import GetDB from './db.mjs'
import StaticProvider from './providers/static.mjs'
import Core from './core.mjs'

export default class ServiceCore {
  constructor(name, root_import_meta_url, dbfilename = 'db.json') {
    if (!root_import_meta_url) {
      throw new Error('ServiceCore must be called with the full string from "import.meta.url" from a file residing in the root directory')
    }
    this._root_import_meta_url = root_import_meta_url
    this.util = new Util(this._root_import_meta_url)
    this.dbfilename = dbname
    this.log = getLog(name)
    this.name = name
    this.config = {}
    this.db = null
    this.core = null
    this.app = null
  }

  async init(module = null) {
    this.db = await GetDB(this.config, this.log, this.dbfilename)
    this.core = new Core(this.db, this.util, this.log)
    
    let provider = new StaticProvider()
    this.app = new Application({
      db: this.db,
      util: this.util,
      log: this.log,
      core: this.core,
    }, provider, this.name)
    this.app.registerModule(module)
  }

  run() {
    return this.app.runVersion('static')
  }
}
