"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processVideosViewsStats = void 0;
const tslib_1 = require("tslib");
const core_utils_1 = require("../../../helpers/core-utils");
const logger_1 = require("../../../helpers/logger");
const video_1 = require("../../../models/video/video");
const video_view_1 = require("../../../models/video/video-view");
const redis_1 = require("../../redis");
function processVideosViewsStats() {
    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
        const lastHour = new Date();
        if (!(0, core_utils_1.isTestInstance)())
            lastHour.setHours(lastHour.getHours() - 1);
        const hour = lastHour.getHours();
        const startDate = lastHour.setMinutes(0, 0, 0);
        const endDate = lastHour.setMinutes(59, 59, 999);
        const videoIds = yield redis_1.Redis.Instance.listVideosViewedForStats(hour);
        if (videoIds.length === 0)
            return;
        logger_1.logger.info('Processing videos views stats in job for hour %d.', hour);
        for (const videoId of videoIds) {
            try {
                const views = yield redis_1.Redis.Instance.getVideoViewsStats(videoId, hour);
                yield redis_1.Redis.Instance.deleteVideoViewsStats(videoId, hour);
                if (views) {
                    logger_1.logger.debug('Adding %d views to video %d stats in hour %d.', views, videoId, hour);
                    try {
                        const video = yield video_1.VideoModel.load(videoId);
                        if (!video) {
                            logger_1.logger.debug('Video %d does not exist anymore, skipping videos view stats.', videoId);
                            continue;
                        }
                        yield video_view_1.VideoViewModel.create({
                            startDate: new Date(startDate),
                            endDate: new Date(endDate),
                            views,
                            videoId
                        });
                    }
                    catch (err) {
                        logger_1.logger.error('Cannot create video views stats for video %d in hour %d.', videoId, hour, { err });
                    }
                }
            }
            catch (err) {
                logger_1.logger.error('Cannot update video views stats of video %d in hour %d.', videoId, hour, { err });
            }
        }
    });
}
exports.processVideosViewsStats = processVideosViewsStats;
//# sourceMappingURL=video-views-stats.js.map