import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState } from "react";
import SimpleDialog from "../SimpleDialog";
import { styled } from "@material-ui/core/styles";
import useElectron from "../../hooks/use-electron";
import ProgressBar from "../ProgressBar";
import { setIn, without } from "seamless-immutable";
import { useTranslation } from "react-i18next";
var ErrorBox = styled("pre")({
  color: "red",
  whiteSpace: "prewrap",
  fontSize: 11
});

var getFfmpegTimeCode = function getFfmpegTimeCode(ms) {
  var cs = Math.floor(ms / 10) % 100;
  var ss = Math.floor(ms / 1000) % 60;
  var mn = Math.floor(ms / 1000 / 60) % 60;
  var hr = Math.floor(ms / 1000 / 60 / 60);
  return [hr, ":", mn, ":", ss, ".", cs].map(function (n) {
    return typeof n === "number" ? n.toString().padStart(2, "0") : n;
  }).join("");
};

export default (function (_ref) {
  var open = _ref.open,
      onChangeDataset = _ref.onChangeDataset,
      onClose = _ref.onClose,
      dataset = _ref.dataset;

  var _ref2 = useElectron() || {},
      remote = _ref2.remote;

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      progress = _useState2[0],
      changeProgress = _useState2[1];

  var _useState3 = useState(""),
      _useState4 = _slicedToArray(_useState3, 2),
      errors = _useState4[0],
      changeErrors = _useState4[1];

  var _useTranslation = useTranslation(),
      t = _useTranslation.t;

  return /*#__PURE__*/React.createElement(SimpleDialog, {
    open: open,
    onClose: onClose,
    title: "Convert Video Frames to Images",
    actions: [{
      text: "Convert Video Frames to Images",
      disabled: progress !== null,
      onClick: function () {
        var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
          var errors, pathToFfmpeg, shell, _remote$require, exec, newsamples, transformsPerformed, i, td, _ret;

          return _regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  changeProgress(0);
                  errors = "";
                  pathToFfmpeg = remote.require("ffmpeg-static");

                  if (!pathToFfmpeg) {
                    changeErrors("There was an issue using ffmpeg. Please create an issue on the github repository.");
                  }

                  shell = remote.require("any-shell-escape");
                  _remote$require = remote.require("child_process"), exec = _remote$require.exec;
                  newsamples = _toConsumableArray(dataset.samples);
                  transformsPerformed = 0;
                  i = 0;

                case 9:
                  if (!(i < dataset.samples.length)) {
                    _context2.next = 20;
                    break;
                  }

                  td = dataset.samples[i];

                  if (!(td.videoUrl && td.videoFrameAt !== undefined)) {
                    _context2.next = 16;
                    break;
                  }

                  return _context2.delegateYield( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
                    var videoPath, imageOutputPath, ffmpegCommand;
                    return _regeneratorRuntime.wrap(function _callee$(_context) {
                      while (1) {
                        switch (_context.prev = _context.next) {
                          case 0:
                            if (!td.videoUrl.startsWith("http")) {
                              _context.next = 3;
                              break;
                            }

                            errors += "Sample ".concat(i, " has a url to a video, videos must be downloaded before extracting frames.");
                            return _context.abrupt("return", "continue");

                          case 3:
                            transformsPerformed++;
                            videoPath = td.videoUrl.replace(/^file:\/\//, "");
                            imageOutputPath = videoPath + "__frameat__" + td.videoFrameAt + ".jpg";
                            ffmpegCommand = shell([pathToFfmpeg, "-y", "-ss", getFfmpegTimeCode(td.videoFrameAt), "-i", videoPath, "-frames:v", 1, imageOutputPath]);
                            _context.next = 9;
                            return new Promise(function (resolve, reject) {
                              exec(ffmpegCommand, {
                                timeout: 5000
                              }, function (err) {
                                if (err) return reject(err);
                                resolve();
                              });
                            });

                          case 9:
                            newsamples[i] = _objectSpread(_objectSpread({}, without(without(dataset.samples[i], "videoUrl"), "videoFrameAt")), {}, {
                              imageUrl: "file://".concat(imageOutputPath)
                            });

                          case 10:
                          case "end":
                            return _context.stop();
                        }
                      }
                    }, _callee);
                  })(), "t0", 13);

                case 13:
                  _ret = _context2.t0;

                  if (!(_ret === "continue")) {
                    _context2.next = 16;
                    break;
                  }

                  return _context2.abrupt("continue", 17);

                case 16:
                  changeProgress(i / dataset.samples.length * 100);

                case 17:
                  i++;
                  _context2.next = 9;
                  break;

                case 20:
                  if (transformsPerformed === 0) {
                    errors += "No transforms were performed, do all of your video samples have frames specified? You may need to convert the keyframes to samples.";
                  }

                  onChangeDataset(setIn(dataset, ["samples"], newsamples));
                  changeErrors(errors);
                  changeProgress(100);

                case 24:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee2);
        }));

        function onClick() {
          return _onClick.apply(this, arguments);
        }

        return onClick;
      }()
    }]
  }, t("transform-video-frames-to-images-dialog-explanation-text"), /*#__PURE__*/React.createElement(ProgressBar, {
    progress: progress || 0
  }), errors && /*#__PURE__*/React.createElement(ErrorBox, null, errors));
});