import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect } from "react";
import Box from "@material-ui/core/Box";
import CircularProgress from "@material-ui/core/CircularProgress";
import SimpleDialog from "../SimpleDialog";
import S3PathSelector from "../S3PathSelector";
import getSampleFromUrl from "../PasteUrlsDialog/get-sample-from-url.js"; // import { useAppConfig } from "../AppConfig"

import useIAMS3API from "../../utils/auth-handlers/use-iam-s3-api";
export var ImportFromS3Dialog = function ImportFromS3Dialog(_ref) {
  var open = _ref.open,
      onClose = _ref.onClose,
      onAddSamples = _ref.onAddSamples;

  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      error = _useState2[0],
      setError = _useState2[1];

  var _useIAMS3API = useIAMS3API(),
      listBuckets = _useIAMS3API.listBuckets,
      listBucketItemsAt = _useIAMS3API.listBucketItemsAt;

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

  var _useState5 = useState({
    optionsLoading: true
  }),
      _useState6 = _slicedToArray(_useState5, 2),
      _useState6$ = _useState6[0],
      options = _useState6$.options,
      optionsLoading = _useState6$.optionsLoading,
      setOptions = _useState6[1];

  useEffect(function () {
    if (!open) return;
    if (!listBuckets) return;

    function loadS3Path() {
      return _loadS3Path.apply(this, arguments);
    }

    function _loadS3Path() {
      _loadS3Path = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var listedBuckets, itemsAtPathRes;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return listBuckets();

              case 2:
                listedBuckets = _context.sent;

                if (!listedBuckets.Error) {
                  _context.next = 6;
                  break;
                }

                setError("Error listing buckets: \nS3 Said: ".concat(listedBuckets.Error.Message));
                return _context.abrupt("return");

              case 6:
                if (!(s3Path === "")) {
                  _context.next = 10;
                  break;
                }

                setOptions({
                  optionsLoading: false,
                  options: listedBuckets.ListAllMyBucketsResult.Buckets.Bucket.map(function (b) {
                    return {
                      name: b.Name,
                      type: "bucket"
                    };
                  })
                });
                _context.next = 17;
                break;

              case 10:
                _context.next = 12;
                return listBucketItemsAt(s3Path);

              case 12:
                itemsAtPathRes = _context.sent;

                if (!itemsAtPathRes.Error) {
                  _context.next = 16;
                  break;
                }

                setError("Error listing buckets at path: \nS3 Said: ".concat(itemsAtPathRes.Error.Message));
                return _context.abrupt("return");

              case 16:
                setOptions({
                  optionsLoading: false,
                  options: (itemsAtPathRes.ListBucketResult.CommonPrefixes || []).map(function (a) {
                    return {
                      name: a.Prefix.split("/").slice(-2).join("/"),
                      type: "directory"
                    };
                  })
                });

              case 17:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));
      return _loadS3Path.apply(this, arguments);
    }

    loadS3Path(); // eslint-disable-next-line
  }, [s3Path, listBuckets, listBucketItemsAt, open]);
  if (!open) return null;

  if (error) {
    return /*#__PURE__*/React.createElement(SimpleDialog, {
      onClose: function onClose() {
        setError(null);
      },
      open: true,
      title: "Error"
    }, /*#__PURE__*/React.createElement("pre", null, error));
  }

  return /*#__PURE__*/React.createElement(SimpleDialog, {
    onClose: onClose,
    open: open,
    title: "Import from S3",
    actions: [{
      onClick: function () {
        var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
          var bucket, items;
          return _regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  bucket = s3Path.match(/s3:\/\/([^/]+)/)[1]; // TODO support more than 1000 file import by using
                  // continuation-token on S3

                  _context2.next = 3;
                  return listBucketItemsAt(s3Path, {
                    files: true
                  });

                case 3:
                  items = _context2.sent.ListBucketResult.Contents.filter(function (item) {
                    return !item.Key.endsWith("/");
                  }).map(function (item) {
                    return "https://s3.amazonaws.com/".concat(bucket, "/").concat(item.Key);
                  }).map(function (url) {
                    return getSampleFromUrl(url, {
                      returnNulls: true
                    });
                  }).filter(Boolean);
                  onAddSamples(items);

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

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

        return onClick;
      }(),
      disabled: !s3Path,
      text: "Import All Files in Directory"
    }]
  }, optionsLoading ? /*#__PURE__*/React.createElement(Box, {
    height: 300,
    width: 400,
    paddingTop: 4,
    textAlign: "center"
  }, /*#__PURE__*/React.createElement(CircularProgress, {
    size: 100
  })) : /*#__PURE__*/React.createElement(S3PathSelector, {
    currentPath: s3Path,
    options: options || [],
    onChangePath: function onChangePath(newS3Path) {
      setS3Path(newS3Path);
      setOptions({
        optionsLoading: true
      });
    }
  }));
};
export default ImportFromS3Dialog;