import _regeneratorRuntime from "@babel/runtime/regenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
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 md5 from "js-md5";
import path from "path";
import { setIn } from "seamless-immutable";
import { useTranslation } from "react-i18next";
var ErrorBox = styled("pre")({
  color: "red",
  whiteSpace: "prewrap",
  fontSize: 11
});

function downloadFile(urlToDownload, directoryPath, remote) {
  var fileName = "sample_".concat(md5(urlToDownload).slice(0, 6), "__").concat(urlToDownload.split("/").slice(-1)[0].replace(/[^a-zA-Z0-9_\-.]/g, ""));
  var downloadPath = path.join(directoryPath, fileName);
  if (remote.require("fs").existsSync(downloadPath)) return downloadPath;
  return new Promise(function (resolve, reject) {
    remote.require("download-file")(urlToDownload, {
      directory: directoryPath,
      filename: fileName
    }, function (err) {
      if (err) return reject(err);
      return resolve(downloadPath);
    });
  });
}

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: "Download URLs",
    actions: [{
      text: "Download URLs",
      disabled: progress !== null,
      onClick: function () {
        var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
          var _yield$remote$dialog$, cancelled, _yield$remote$dialog$2, _yield$remote$dialog$3, directoryPath, newSamples, errors, i, td, urlKey, urlToDownload, pathToFile;

          return _regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  changeProgress(0);
                  _context.next = 3;
                  return remote.dialog.showOpenDialog({
                    title: "Directory to download files to",
                    buttonLabel: "Download Files Here",
                    properties: ["createDirectory", "openDirectory", "promptToCreate"]
                  });

                case 3:
                  _yield$remote$dialog$ = _context.sent;
                  cancelled = _yield$remote$dialog$.cancelled;
                  _yield$remote$dialog$2 = _yield$remote$dialog$.filePaths;
                  _yield$remote$dialog$2 = _yield$remote$dialog$2 === void 0 ? [null] : _yield$remote$dialog$2;
                  _yield$remote$dialog$3 = _slicedToArray(_yield$remote$dialog$2, 1), directoryPath = _yield$remote$dialog$3[0];

                  if (!(cancelled || !directoryPath)) {
                    _context.next = 11;
                    break;
                  }

                  changeProgress(null);
                  return _context.abrupt("return");

                case 11:
                  newSamples = _toConsumableArray(dataset.samples);
                  errors = ""; // Iterate over each task datum and download the url, then convert
                  // the path to a filesystem path

                  i = 0;

                case 14:
                  if (!(i < dataset.samples.length)) {
                    _context.next = 36;
                    break;
                  }

                  td = dataset.samples[i];
                  urlKey = void 0;
                  if (td.imageUrl) urlKey = "imageUrl";
                  if (td.videoUrl) urlKey = "videoUrl";

                  if (!(!urlKey || !td[urlKey].startsWith("http"))) {
                    _context.next = 21;
                    break;
                  }

                  return _context.abrupt("continue", 33);

                case 21:
                  urlToDownload = td[urlKey];
                  _context.prev = 22;
                  _context.next = 25;
                  return downloadFile(urlToDownload, directoryPath, remote);

                case 25:
                  pathToFile = _context.sent;
                  newSamples[i] = _objectSpread(_objectSpread({}, td), {}, _defineProperty({}, urlKey, "file://".concat(pathToFile)));
                  _context.next = 32;
                  break;

                case 29:
                  _context.prev = 29;
                  _context.t0 = _context["catch"](22);
                  errors += "Skipping sample, error downloading samples[".concat(i, "] (").concat(urlToDownload, "): ").concat(_context.t0.toString(), " \n");

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

                case 33:
                  i++;
                  _context.next = 14;
                  break;

                case 36:
                  onChangeDataset(setIn(dataset, ["samples"], newSamples));
                  changeErrors(errors);
                  changeProgress(100);

                case 39:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[22, 29]]);
        }));

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

        return onClick;
      }()
    }]
  }, t("download-urls-dialog"), /*#__PURE__*/React.createElement(ProgressBar, {
    progress: progress || 0
  }), errors && /*#__PURE__*/React.createElement(ErrorBox, null, errors));
});