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

export default class ServiceCore {
  constructor(name, root_import_meta_url, port = 4000, 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 = dbfilename
    this.log = getLog(name)
    this.name = name
    this.config = {}
    this.db = null
    this.core = null
    this.app = null

    this.setConfig({
      port: port,
    })
  }

  setConfig(config) {
    this.config[this.name] = config
  }

  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')
  }
}
