"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var CacheOnIntervalService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheOnIntervalService = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const chalk_1 = __importDefault(require("chalk"));
const file_system_cache_1 = __importDefault(require("file-system-cache"));
const lodash_1 = require("lodash");
const cache_on_interval_decorator_1 = require("./cache-on-interval.decorator");
let CacheOnIntervalService = CacheOnIntervalService_1 = class CacheOnIntervalService {
    constructor(discoveryService, metadataScanner, reflector) {
        this.discoveryService = discoveryService;
        this.metadataScanner = metadataScanner;
        this.reflector = reflector;
        this.intervals = [];
        this.registeredCacheKeys = [];
        this.logger = new common_1.Logger(CacheOnIntervalService_1.name);
        this.cacheManager = (0, file_system_cache_1.default)({
            basePath: './.cache',
            ns: '@CacheOnInterval',
        });
    }
    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.registerCache(wrapper.instance, methodName);
            });
        });
    }
    onModuleDestroy() {
        this.intervals.forEach(interval => clearInterval(interval));
    }
    checkCacheConflicts(cacheKey) {
        if (this.registeredCacheKeys.includes(cacheKey)) {
            throw new Error(`Cache conflict found for key "${cacheKey}"`);
        }
        this.registeredCacheKeys.push(cacheKey);
    }
    registerCache(instance, methodName) {
        const logger = this.logger;
        const methodRef = instance[methodName];
        const opts = this.reflector.get(cache_on_interval_decorator_1.CACHE_ON_INTERVAL_OPTIONS, methodRef);
        if (!opts)
            return;
        const { key: cacheKey, timeout: cacheTimeout } = opts;
        try {
            this.checkCacheConflicts(cacheKey);
        }
        catch (e) {
            this.logger.error(e.message);
        }
        const cacheManager = this.cacheManager;
        instance[methodName] = function () {
            return __awaiter(this, void 0, void 0, function* () {
                const cachedValue = yield cacheManager.get(cacheKey);
                if ((0, lodash_1.isUndefined)(cachedValue)) {
                    logger.warn(`@CacheOnInterval has no cache primed for ${instance.constructor.name}#${methodName}. Please wait for a few seconds as the cache is primed.`);
                }
                return cachedValue;
            });
        };
        let liveData = methodRef.apply(instance);
        if (!liveData.then) {
            liveData = new Promise(liveData);
        }
        liveData
            .then((d) => {
            return cacheManager.set(cacheKey, d);
        })
            .then(() => {
            logger.log(`Cache ready for for ${instance.constructor.name}#${methodName}`);
        })
            .catch((e) => {
            logger.error(`@CacheOnInterval error init for ${instance.constructor.name}#${methodName}: ${e.message}`);
            logger.error(chalk_1.default.gray(e.stack));
        });
        const interval = setInterval(() => {
            methodRef
                .apply(instance)
                .then((liveData) => {
                cacheManager.set(cacheKey, liveData).catch((e) => {
                    logger.error(`@CacheOnInterval caching error for ${instance.constructor.name}#${methodName}: ${e.message}`);
                    logger.error(chalk_1.default.gray(e.stack));
                });
            })
                .catch((e) => {
                logger.error(`@CacheOnInterval target error for ${instance.constructor.name}#${methodName}: ${e.message}`);
                logger.error(chalk_1.default.gray(e.stack));
            });
        }, cacheTimeout);
        this.intervals.push(interval);
    }
};
CacheOnIntervalService = CacheOnIntervalService_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])
], CacheOnIntervalService);
exports.CacheOnIntervalService = CacheOnIntervalService;
//# sourceMappingURL=cache-on-interval.service.js.map