const CanonicalUnit = require('libflitter/canon/CanonicalUnit')
const LDAPController = require('../ldap/controllers/LDAPController')
const StopError = require('libflitter/errors/StopError')

class LDAPControllerUnit extends CanonicalUnit {
    static get name() {
        return 'ldap_controllers'
    }

    static get services() {
        return [...super.services, 'output']
    }

    constructor(base_directory = './app/ldap/controllers') {
        super(base_directory)

        this.canonical_item = 'ldap_controller'
        this.suffix = '.controller.js'
    }

    async init_canonical_file({app, name, instance}) {
        if ( instance.prototype instanceof LDAPController ) {
            this.output.debug(`Registering LDAP controller: ${name}`)
            return new instance()
        } else {
            this.output.error(`LDAP Controller ${name} must extend base class LDAPController.`)
            throw new StopError(`LDAP Controller ${name} must extend base class LDAPController.`)
        }
    }

    /**
     * Resolve an unqualified canonical name to a registered canonical controller or method.
     * @param {string} name
     // * @returns {module:libflitter/controller/Controller~Controller|function}
     */
    get(name) {
        const name_parts = name.split('.')
        const controller_instance = this.canonical_items[name_parts[0]]

        if ( name_parts.length > 1 ) {
            const method_instance = controller_instance[name_parts[1]].bind(controller_instance)

            if ( name_parts > 2 ) {
                let descending_value = method_instance
                name_parts.slice(2).forEach(part => {
                    descending_value = descending_value[part]
                })

                return descending_value
            } else {
                return method_instance
            }
        }

        // TODO this is a bug in libflitter too!
        return controller_instance
    }
}

module.exports = exports = LDAPControllerUnit
