"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../api/reels/models");
function isCompressed(url) {
    const filename = url.split('.').at(-2);
    return !!(filename === null || filename === void 0 ? void 0 : filename.endsWith('-compressed'));
}
function uncompress(url) {
    const split = url.split('.');
    let filename = split.at(-2);
    if (filename === null || filename === void 0 ? void 0 : filename.endsWith('-compressed')) {
        filename = filename.substring(0, filename.length - '-compressed'.length);
    }
    let newSplit = [...split.slice(0, split.length - 2), filename, split.at(-1)];
    return newSplit.join('.');
}
function execute() {
    return __awaiter(this, void 0, void 0, function* () {
        const reels = yield models_1.Reel.find();
        console.log('');
        for (let i = 0; i < reels.length; i++) {
            const reel = reels[i];
            let flag = false;
            if (reel.video && isCompressed(reel.video)) {
                reel.video = uncompress(reel.video);
                flag = true;
            }
            if (reel.dynamic) {
                for (const d of reel.dynamic) {
                    if (isCompressed(d.video)) {
                        d.video = uncompress(d.video);
                        flag = true;
                    }
                }
            }
            if (flag) {
                console.log('\rreel', reel._id.toString(), 'reverting');
                yield reel.save();
            }
            yield new Promise((r) => setTimeout(r, 100));
            process.stdout.write(`\r${i + 1}/${reels.length}`);
        }
        console.log('\r✅ Done            ');
    });
}
const scriptRevertCompressedReels = {
    isCompressed,
    uncompress,
    execute
};
exports.default = scriptRevertCompressedReels;
