import Context from 'skypager-registry/lib/context'
import Helper from '../helper'

export class ConfigBuilder extends Helper {
  static isCacheable = true

  static cacheable(setting = true) {
    return this.isCacheable = !!setting
  }

  static createRegistry = (options = {}) => new Context('configBuilders', {
    context: require.context('../config-builders', false, /.js$/),
    ...options,
    sourceModule: {
      id: (module && module.id) || __filename,
      filename: __filename, dirname: __dirname,
      ...options.sourceModule || {},
    },
  })

  static attach(project, options = {}) {
    return Helper.attach(project, ConfigBuilder, {
      registryProp: 'configBuilders',
      lookupProp: 'configBuilder',
      registry: options.registry || ConfigBuilder.createRegistry(),
      ...options,
    })
  }

  initialize() {
    const api = this.api = this.build(this.options)

    Object.keys(this.api).forEach(key => {
      Object.assign(this, {
        get [key]() {
          return api[key]
        }
      })
    })
  }

  build(options = {}) {
    return this.cached = this.cached || this.provider.api({
      features: this.features,
      reducers: this.reducers,
      scope: this.project,
    }, this.context)
  }

  get features() {
    return this.result('provider.features', this.result('provider.defaultFeatures', () => ({})))
  } 

  get reducers() {
    return this.result('provider.reducers', this.result('provider.defaultReducers', () => ({})))
  } 

  get config() {
    return this.api.getConfig()
  }
}

export default ConfigBuilder

export const attach = ConfigBuilder.attach
