"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const iterare_1 = require("iterare");
require("reflect-metadata");
const context_creator_1 = require("../helpers/context-creator");
class InterceptorsContextCreator extends context_creator_1.ContextCreator {
    constructor(container, config) {
        super();
        this.container = container;
        this.config = config;
    }
    create(instance, callback, module) {
        this.moduleContext = module;
        return this.createContext(instance, callback, constants_1.INTERCEPTORS_METADATA);
    }
    createConcreteContext(metadata) {
        if (shared_utils_1.isUndefined(metadata) || shared_utils_1.isEmpty(metadata)) {
            return [];
        }
        return iterare_1.default(metadata)
            .filter((interceptor) => interceptor && (interceptor.name || interceptor.intercept))
            .map(interceptor => this.getInterceptorInstance(interceptor))
            .filter((interceptor) => interceptor && shared_utils_1.isFunction(interceptor.intercept))
            .toArray();
    }
    getInterceptorInstance(interceptor) {
        const isObject = interceptor.intercept;
        if (isObject) {
            return interceptor;
        }
        const instanceWrapper = this.getInstanceByMetatype(interceptor);
        return instanceWrapper && instanceWrapper.instance
            ? instanceWrapper.instance
            : null;
    }
    getInstanceByMetatype(metatype) {
        if (!this.moduleContext) {
            return undefined;
        }
        const collection = this.container.getModules();
        const module = collection.get(this.moduleContext);
        if (!module) {
            return undefined;
        }
        return module.injectables.get(metatype.name);
    }
    getGlobalMetadata() {
        if (!this.config) {
            return [];
        }
        return this.config.getGlobalInterceptors();
    }
}
exports.InterceptorsContextCreator = InterceptorsContextCreator;
