const CanonicalUnit = require('libflitter/canon/CanonicalUnit')
const LDAPMiddleware = require('../ldap/middleware/LDAPMiddleware')
const StopError = require('libflitter/errors/StopError')

class LDAPMiddlewareUnit extends CanonicalUnit {
    static get services() {
        return [...super.services, 'output']
    }

    static get name() {
        return 'ldap_middleware'
    }

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

        this.canonical_item = 'ldap_middleware'
        this.suffix = '.middleware.js'
    }

    async init_canonical_file({app, name, instance}) {
        if ( instance.prototype instanceof LDAPMiddleware ) {
            this.output.debug(`Registering LDAP middleware: ${name}`)
            return new instance()
        } else {
            this.output.error(`LDAP middleware class ${name} must be an instance of LDAPMiddleware.`)
            throw new StopError(`LDAP middleware class ${name} must be an instance of LDAPMiddleware.`)
        }
    }

    get(name) {
        const item = super.get(name)
        if ( item instanceof LDAPMiddleware ) {
            return item.test.bind(item)
        }

        return item
    }
}

module.exports = exports = LDAPMiddlewareUnit
