"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var SchedulerService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchedulerService = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const chalk_1 = __importDefault(require("chalk"));
const scheduler_decorator_1 = require("./scheduler.decorator");
let SchedulerService = SchedulerService_1 = class SchedulerService {
    constructor(discoveryService, metadataScanner, reflector) {
        this.discoveryService = discoveryService;
        this.metadataScanner = metadataScanner;
        this.reflector = reflector;
        this.intervals = [];
        this.logger = new common_1.Logger(SchedulerService_1.name);
    }
    onModuleInit() {
        const instanceWrappers = this.discoveryService.getProviders();
        instanceWrappers
            .filter(wrapper => wrapper.isDependencyTreeStatic() && !!wrapper.instance)
            .forEach(wrapper => {
            this.metadataScanner.scanFromPrototype(wrapper.instance, Object.getPrototypeOf(wrapper.instance), (methodName) => {
                this.registerSchedule(wrapper.instance, methodName);
            });
        });
    }
    onModuleDestroy() {
        this.intervals.forEach(interval => clearInterval(interval));
    }
    registerSchedule(instance, methodName) {
        const logger = this.logger;
        const methodRef = instance[methodName];
        const opts = this.reflector.get(scheduler_decorator_1.SCHEDULER_OPTIONS, methodRef);
        if (!opts)
            return;
        let liveData = methodRef.apply(instance);
        if (!liveData.then) {
            liveData = new Promise(liveData);
        }
        liveData
            .then(() => {
            logger.log(`@Schedule executed for ${instance.constructor.name}#${methodName}`);
        })
            .catch((e) => {
            logger.error(`@Schedule error init for ${instance.constructor.name}#${methodName}: ${e.message}`);
            logger.error(chalk_1.default.gray(e.stack));
        });
        const interval = setInterval(() => {
            methodRef.apply(instance).catch((e) => {
                logger.error(`@Schedule target error for ${instance.constructor.name}#${methodName}: ${e.message}`);
                logger.error(chalk_1.default.gray(e.stack));
            });
        }, opts.every);
        this.intervals.push(interval);
    }
};
SchedulerService = SchedulerService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)(core_1.DiscoveryService)),
    __param(1, (0, common_1.Inject)(core_1.MetadataScanner)),
    __param(2, (0, common_1.Inject)(core_1.Reflector)),
    __metadata("design:paramtypes", [core_1.DiscoveryService,
        core_1.MetadataScanner,
        core_1.Reflector])
], SchedulerService);
exports.SchedulerService = SchedulerService;
//# sourceMappingURL=scheduler.service.js.map