"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VideoViewsBufferScheduler = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("../../helpers/logger");
const video_1 = require("../../models/video/video");
const constants_1 = require("../../initializers/constants");
const videos_1 = require("../activitypub/videos");
const redis_1 = require("../redis");
const abstract_scheduler_1 = require("./abstract-scheduler");
const lTags = (0, logger_1.loggerTagsFactory)('views');
class VideoViewsBufferScheduler extends abstract_scheduler_1.AbstractScheduler {
    constructor() {
        super();
        this.schedulerIntervalMs = constants_1.SCHEDULER_INTERVALS_MS.VIDEO_VIEWS_BUFFER_UPDATE;
    }
    internalExecute() {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
            const videoIds = yield redis_1.Redis.Instance.listLocalVideosViewed();
            if (videoIds.length === 0)
                return;
            logger_1.logger.info('Processing local video views buffer.', Object.assign({ videoIds }, lTags()));
            for (const videoId of videoIds) {
                try {
                    const views = yield redis_1.Redis.Instance.getLocalVideoViews(videoId);
                    yield redis_1.Redis.Instance.deleteLocalVideoViews(videoId);
                    const video = yield video_1.VideoModel.loadAndPopulateAccountAndServerAndTags(videoId);
                    if (!video) {
                        logger_1.logger.debug('Video %d does not exist anymore, skipping videos view addition.', videoId, lTags());
                        continue;
                    }
                    yield video_1.VideoModel.incrementViews(videoId, views);
                    video.views += views;
                    yield (0, videos_1.federateVideoIfNeeded)(video, false);
                }
                catch (err) {
                    logger_1.logger.error('Cannot process local video views buffer of video %d.', videoId, Object.assign({ err }, lTags()));
                }
            }
        });
    }
    static get Instance() {
        return this.instance || (this.instance = new this());
    }
}
exports.VideoViewsBufferScheduler = VideoViewsBufferScheduler;
//# sourceMappingURL=video-views-buffer-scheduler.js.map