import path from 'path'
import fs from 'fs'

export default class ModuleConfiguration {
  constructor(options) {
    this.manager = options.manager
    this.module = options.module
    this.logger = options.logger
    this.configLocation = options.configLocation
  }

  _getFileName() {
    const sanitizedName = this.module.name
      .replace(/^@botpress(-)?\//i, '')
      .replace(/^botpress(-)?/i, '')
      .replace(path.delimiter, '_')

    return `${sanitizedName}.json`
  }

  _getOptions() {
    return this.module.options
  }

  _hasDefaultConfig() {
    const filePath = path.resolve(this.module.path, 'config.json')
    return fs.existsSync(filePath)
  }

  _readDefaultConfig() {
    const filePath = path.resolve(this.module.path, 'config.json')
    return fs.readFileSync(filePath, 'utf8')
  }

  async loadAll(caching = true) {
    return this.manager.loadAll(this._getFileName(), this._getOptions(), caching)
  }

  async get(key, caching = true) {
    return this.manager.get(this._getFileName(), key, this._getOptions(), caching)
  }

  /**
   * Copy the module's default configuration file to the bot's config directory
   */
  async bootstrap() {
    if (!this._hasDefaultConfig()) {
      return
    }

    const file = this._getFileName()
    const filePath = path.resolve(this.configLocation, file)
    const content = this._readDefaultConfig()

    fs.writeFileSync(filePath, content, 'utf8')
    this.logger.info(`Configuration for module "${this.module.name}" has been created at ${filePath}`)
  }

  /**
   * Checks whether the module has a configuration file
   * and if the bot doesn't have the configuration file for it.
   * @return {Boolean}
   */
  async isConfigMissing() {
    const file = this._getFileName()
    const filePath = path.resolve(this.configLocation, file)

    console.log(this._hasDefaultConfig(), filePath)
    return this._hasDefaultConfig() && !fs.existsSync(filePath)
  }
}

@@ -36,16 +36,39 @@
 rom 'fs'
+%0Aimport _ from 'lodash'
 %0A%0Aexport
@@ -857,38 +857,52 @@
 g = true) %7B%0A    
-return
+const config = await
  this.manager.lo
@@ -948,32 +948,454 @@
 ions(), caching)
+%0A%0A    const file = this._getFileName()%0A    const filePath = path.resolve(this.configLocation, file)%0A%0A    _.mapValues(config, (value, key) =%3E %7B%0A      if (value === '%3C%3CUPDATE_ME%3E%3E') %7B%0A        const message = %60%5B$%7Bthis.module.name%7D%5D Missing mandatory configuration for %22$%7Bkey%7D%22. %0AYou can provide this value in %22$%7BfilePath%7D%22%60%0A        this.logger.error(message)%0A        throw new Error(message)%0A      %7D%0A    %7D)%0A%0A    return config
 %0A  %7D%0A%0A  async ge
@@ -2191,32 +2191,32 @@
 ._getFileName()%0A
+
     const filePa
@@ -2263,61 +2263,8 @@
 ile)
-%0A%0A    console.log(this._hasDefaultConfig(), filePath)
 %0A   

throw if there's missing mandatory config keys