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

export class ProjectType extends Helper {
  static isCacheable = true

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

  static createRegistry = () => new Context('projectTypes', {
    context: require.context('../project-types', false, /.js$/),
  })

  static attach(project, options = {}) {
    return Helper.attach(project, ProjectType, {
      registryProp: 'projectTypes',
      lookupProp: 'projectType',
      registry: options.registry || ProjectType.createRegistry(),
      ...options,
    })
  }

  attach(options = {}, context = {}) {
    try {
      if (this.provider && this.provider.attach) {
        this.provider.attach.call(this.project, {...this.options, ...options}, {project: this.project, ...this.context, ...context}) 
      }  
    } catch(error) {
      console.error(error)
      throw new Error(`Error while attaching ${this.name} project type`)
    }

    return this
  }
  
  use() {
    if (this.provider && this.provider.use) {
      this.project.use(this.provider.use.bind(this.project))
    }

    return this
  }
}

export default ProjectType

export const attach = ProjectType.attach
