import _regeneratorRuntime from "@babel/runtime/regenerator";
import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import React, { useState } from "react";
import SimpleDialog from "../SimpleDialog";
import { setIn } from "seamless-immutable";
import ProgressBar from "../ProgressBar";
import useDataset from "../../hooks/use-dataset";

function isUrlValid(_x) {
  return _isUrlValid.apply(this, arguments);
}

function _isUrlValid() {
  _isUrlValid = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(url) {
    return _regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            return _context3.abrupt("return", new Promise(function (resolve) {
              var image = document.createElement("img");

              image.onload = function () {
                resolve(true);
              };

              image.onerror = function () {
                resolve(false);
              };

              image.src = url;
              setTimeout(function () {
                resolve(true);
              }, 200);
            }));

          case 1:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _isUrlValid.apply(this, arguments);
}

export default (function (_ref) {
  var _dataset$samples, _dataset$samples2;

  var open = _ref.open,
      onClose = _ref.onClose;

  var _useDataset = useDataset(),
      _useDataset2 = _slicedToArray(_useDataset, 2),
      dataset = _useDataset2[0],
      setDataset = _useDataset2[1]; // const [errors, setErrors] = useState("")


  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      filteredSamples = _useState2[0],
      setFilteredSamples = _useState2[1];

  var _useState3 = useState({
    samplesRemoved: 0,
    samplesProcessed: 0,
    complete: false
  }),
      _useState4 = _slicedToArray(_useState3, 2),
      _useState4$ = _useState4[0],
      samplesRemoved = _useState4$.samplesRemoved,
      samplesProcessed = _useState4$.samplesProcessed,
      complete = _useState4$.complete,
      setProcessState = _useState4[1];

  return /*#__PURE__*/React.createElement(SimpleDialog, {
    open: open,
    onClose: onClose,
    title: "Remove Invalid Samples",
    actions: [{
      text: "Find Invalid Samples",
      onClick: function () {
        var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
          var samples, samplesProcessed, samplesRemoved, _iterator, _step, sample, requestUrl;

          return _regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  samples = [];
                  samplesProcessed = 0, samplesRemoved = 0; // TODO add parallelism

                  _iterator = _createForOfIteratorHelper(dataset.samples);
                  _context.prev = 3;

                  _iterator.s();

                case 5:
                  if ((_step = _iterator.n()).done) {
                    _context.next = 21;
                    break;
                  }

                  sample = _step.value;
                  setProcessState({
                    samplesRemoved: samplesRemoved,
                    samplesProcessed: samplesProcessed,
                    complete: false
                  });
                  samplesProcessed += 1;
                  requestUrl = sample.imageUrl;

                  if (!(!requestUrl || !requestUrl.startsWith("http"))) {
                    _context.next = 13;
                    break;
                  }

                  samples.push(sample);
                  return _context.abrupt("continue", 19);

                case 13:
                  _context.next = 15;
                  return isUrlValid(requestUrl);

                case 15:
                  if (!_context.sent) {
                    _context.next = 18;
                    break;
                  }

                  samples.push(sample);
                  return _context.abrupt("continue", 19);

                case 18:
                  samplesRemoved += 1;

                case 19:
                  _context.next = 5;
                  break;

                case 21:
                  _context.next = 26;
                  break;

                case 23:
                  _context.prev = 23;
                  _context.t0 = _context["catch"](3);

                  _iterator.e(_context.t0);

                case 26:
                  _context.prev = 26;

                  _iterator.f();

                  return _context.finish(26);

                case 29:
                  setProcessState({
                    samplesRemoved: samplesRemoved,
                    samplesProcessed: samplesProcessed,
                    complete: true
                  });
                  setFilteredSamples(samples);

                case 31:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[3, 23, 26, 29]]);
        }));

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

        return onClick;
      }()
    }, complete && {
      text: "Remove Invalid Samples",
      onClick: function () {
        var _onClick2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
          return _regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  setDataset(setIn(dataset, ["samples"], filteredSamples));

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

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

        return onClick;
      }()
    }].filter(Boolean)
  }, /*#__PURE__*/React.createElement(ProgressBar, {
    progress: complete ? 100 : samplesProcessed / (((_dataset$samples = dataset.samples) === null || _dataset$samples === void 0 ? void 0 : _dataset$samples.length) + 1) * 100
  }), /*#__PURE__*/React.createElement("div", null, "Samples processed: ", samplesProcessed, /*#__PURE__*/React.createElement("br", null), "Samples to be removed: ", samplesRemoved, /*#__PURE__*/React.createElement("br", null), "Total samples: ", (_dataset$samples2 = dataset.samples) === null || _dataset$samples2 === void 0 ? void 0 : _dataset$samples2.length), /*#__PURE__*/React.createElement("div", {
    style: {
      marginTop: 16
    }
  }, "This transformation will try to request each sample's url, if any of them do not return a valid status code the sample will be removed from the dataset."));
});