"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LiveSegmentShaStore = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const core_utils_1 = require("../../helpers/core-utils");
const logger_1 = require("../../helpers/logger");
const hls_1 = require("../hls");
const object_storage_1 = require("../object-storage");
const p_queue_1 = tslib_1.__importDefault(require("p-queue"));
const lTags = (0, logger_1.loggerTagsFactory)('live');
class LiveSegmentShaStore {
    constructor(options) {
        this.segmentsSha256 = new Map();
        this.writeQueue = new p_queue_1.default({ concurrency: 1 });
        this.videoUUID = options.videoUUID;
        this.sha256Path = options.sha256Path;
        this.streamingPlaylist = options.streamingPlaylist;
        this.sendToObjectStorage = options.sendToObjectStorage;
    }
    addSegmentSha(segmentPath) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            logger_1.logger.debug('Adding live sha segment %s.', segmentPath, lTags(this.videoUUID));
            const shaResult = yield (0, hls_1.buildSha256Segment)(segmentPath);
            const segmentName = (0, path_1.basename)(segmentPath);
            this.segmentsSha256.set(segmentName, shaResult);
            try {
                yield this.writeToDisk();
            }
            catch (err) {
                logger_1.logger.error('Cannot write sha segments to disk.', { err });
            }
        });
    }
    removeSegmentSha(segmentPath) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const segmentName = (0, path_1.basename)(segmentPath);
            logger_1.logger.debug('Removing live sha segment %s.', segmentPath, lTags(this.videoUUID));
            if (!this.segmentsSha256.has(segmentName)) {
                logger_1.logger.warn('Unknown segment in files map for video %s and segment %s.', this.videoUUID, segmentPath, lTags(this.videoUUID));
                return;
            }
            this.segmentsSha256.delete(segmentName);
            yield this.writeToDisk();
        });
    }
    writeToDisk() {
        return this.writeQueue.add(() => tslib_1.__awaiter(this, void 0, void 0, function* () {
            yield (0, fs_extra_1.writeJson)(this.sha256Path, (0, core_utils_1.mapToJSON)(this.segmentsSha256));
            if (this.sendToObjectStorage) {
                const url = yield (0, object_storage_1.storeHLSFileFromPath)(this.streamingPlaylist, this.sha256Path);
                if (this.streamingPlaylist.segmentsSha256Url !== url) {
                    this.streamingPlaylist.segmentsSha256Url = url;
                    yield this.streamingPlaylist.save();
                }
            }
        }));
    }
}
exports.LiveSegmentShaStore = LiveSegmentShaStore;
//# sourceMappingURL=live-segment-sha-store.js.map