var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { Plugin } from '@magic-circle/schema';
import { Store } from '@magic-circle/state';
import { registerIcon, VideoCamera } from '@magic-circle/styles';
import Sidebar from './Sidebar';
registerIcon(VideoCamera);
var Recordings = /** @class */ (function (_super) {
    __extends(Recordings, _super);
    function Recordings() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.name = 'recordings';
        _this.current = new Store({
            width: 1080,
            height: 720,
            fps: 30,
            duration: 15,
            frame: 0,
            directory: null,
            isRecording: false,
            sync: false,
        });
        return _this;
    }
    Recordings.prototype.setup = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                this.ipc.on('recordings:save', function (_, data) {
                    _this.saveScreenshot(data);
                });
                return [2 /*return*/];
            });
        });
    };
    Recordings.prototype.sidebar = function () {
        return {
            icon: 'VideoCamera',
            name: 'recording',
            after: 'screenshots',
            render: <Sidebar recordings={this}/>,
        };
    };
    Recordings.prototype.start = function () {
        return __awaiter(this, void 0, void 0, function () {
            var timeline, base, permission, now, date, time, fileName, directory, _a, width, height, fps;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.screenshots = this.app.getPlugin('screenshots');
                        if (!this.screenshots) {
                            throw new Error('The screenshot plugin is needed to use the recordings plugin');
                        }
                        timeline = this.app.getPlugin('timeline');
                        if (this.current.value.sync && timeline) {
                            timeline.setPlayhead(0);
                            timeline.play();
                        }
                        return [4 /*yield*/, this.screenshots.getDirectory()];
                    case 1:
                        base = _b.sent();
                        return [4 /*yield*/, this.screenshots.verifyPermission(base, false)];
                    case 2:
                        permission = _b.sent();
                        if (!permission) {
                            // todo do something
                            return [2 /*return*/];
                        }
                        now = new Date();
                        date = "".concat(now.getFullYear(), "-").concat(now.getMonth() + 1, "-").concat(now.getDate());
                        time = "".concat(now.getHours(), ".").concat(now.getMinutes());
                        fileName = "".concat(date, " ").concat(time);
                        return [4 /*yield*/, base.getDirectoryHandle("recording ".concat(fileName), {
                                create: true,
                            })];
                    case 3:
                        directory = _b.sent();
                        if (!directory) {
                            // todo do something
                            return [2 /*return*/];
                        }
                        this.current.set(__assign(__assign({}, this.current.value), { isRecording: true, frame: 0, directory: directory }));
                        _a = this.current.value, width = _a.width, height = _a.height, fps = _a.fps;
                        this.ipc.send('recordings:start', {
                            width: width,
                            height: height,
                            fps: fps,
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    Recordings.prototype.next = function () {
        this.current.set(__assign(__assign({}, this.current.value), { frame: this.current.value.frame + 1 }));
        // see if we went over the time
        var _a = this.current.value, duration = _a.duration, fps = _a.fps, frame = _a.frame;
        var maxFrames = duration * fps;
        if (frame < maxFrames) {
            this.ipc.send('recordings:next');
        }
        else {
            this.finish();
        }
    };
    Recordings.prototype.finish = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, directory, duration, fps, width, height, maxFrames, digits, script, fileHandle, writable;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.current.value, directory = _a.directory, duration = _a.duration, fps = _a.fps, width = _a.width, height = _a.height;
                        maxFrames = duration * fps;
                        digits = String(maxFrames).length;
                        script = "ffmpeg -r ".concat(fps, " -f image2 -s ").concat(width, "x").concat(height, " -i frame-%0").concat(digits, "d.png -vcodec libx264 -crf 15  -pix_fmt yuv420p \"recording.mp4\"");
                        return [4 /*yield*/, directory.getFileHandle("convert.sh", {
                                create: true,
                            })];
                    case 1:
                        fileHandle = _b.sent();
                        return [4 /*yield*/, fileHandle.createWritable()];
                    case 2:
                        writable = _b.sent();
                        return [4 /*yield*/, writable.write(script)];
                    case 3:
                        _b.sent();
                        return [4 /*yield*/, writable.close()];
                    case 4:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    Recordings.prototype.saveScreenshot = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, directory, duration, fps, frame, maxFrames, digits, number;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.current.value, directory = _a.directory, duration = _a.duration, fps = _a.fps, frame = _a.frame;
                        maxFrames = duration * fps;
                        digits = String(maxFrames).length;
                        number = String(frame).padStart(digits, '0');
                        if (!this.screenshots) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.screenshots.saveScreenshotTo(directory, "frame-".concat(number), data, false)];
                    case 1:
                        _b.sent();
                        requestAnimationFrame(function () {
                            _this.next();
                        });
                        _b.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    return Recordings;
}(Plugin));
export default Recordings;
