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, useRef } 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 IconButton from "@material-ui/core/IconButton";
import BackIcon from "@material-ui/icons/KeyboardArrowLeft"; // import { useAppConfig } from "../AppConfig"

import { styled } from "@material-ui/core/styles";
import * as colors from "@material-ui/core/colors";
import useIAMS3API from "../../utils/auth-handlers/use-iam-s3-api";
import MultiFileDrop from "../MultiFileDrop";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
var SelectedPath = styled("div")({
  fontSize: 14,
  color: colors.grey[700],
  fontWeight: "bold"
});
export var UploadToS3Dialog = function UploadToS3Dialog(_ref) {
  var open = _ref.open,
      onClose = _ref.onClose,
      onAddSamples = _ref.onAddSamples;

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

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      complete = _useState2[0],
      setComplete = _useState2[1];

  var uploadedPaths = useRef([]);

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

  var _useState5 = useState(0),
      _useState6 = _slicedToArray(_useState5, 2),
      activeStep = _useState6[0],
      setActiveStep = _useState6[1];

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

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

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

    function _loadS3Path() {
      _loadS3Path = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!(s3Path === "")) {
                  _context.next = 9;
                  break;
                }

                _context.t0 = setOptions;
                _context.next = 4;
                return listBuckets();

              case 4:
                _context.t1 = _context.sent.ListAllMyBucketsResult.Buckets.Bucket.map(function (b) {
                  return {
                    name: b.Name,
                    type: "bucket"
                  };
                });
                _context.t2 = {
                  optionsLoading: false,
                  options: _context.t1
                };
                (0, _context.t0)(_context.t2);
                _context.next = 18;
                break;

              case 9:
                _context.t3 = setOptions;
                _context.next = 12;
                return listBucketItemsAt(s3Path);

              case 12:
                _context.t4 = _context.sent.ListBucketResult.CommonPrefixes;

                if (_context.t4) {
                  _context.next = 15;
                  break;
                }

                _context.t4 = [];

              case 15:
                _context.t5 = _context.t4.map(function (a) {
                  return {
                    name: a.Prefix.split("/").slice(-2).join("/"),
                    type: "directory"
                  };
                });
                _context.t6 = {
                  optionsLoading: false,
                  options: _context.t5
                };
                (0, _context.t3)(_context.t6);

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

    loadS3Path(); // eslint-disable-next-line
  }, [open, s3Path, listBuckets, listBucketItemsAt]);
  if (!open) return null;
  return /*#__PURE__*/React.createElement(SimpleDialog, {
    onClose: onClose,
    open: open,
    title: "Upload to S3",
    actions: [activeStep === 0 && {
      onClick: function onClick() {
        return setActiveStep(1);
      },
      disabled: !s3Path,
      text: "Upload to this directory"
    }, activeStep === 1 && {
      disabled: !complete,
      onClick: function onClick() {
        var samples = uploadedPaths.current.map(function (url) {
          return getSampleFromUrl(url, {
            returnNulls: true
          });
        }).filter(Boolean);
        onAddSamples(samples);
      },
      text: "Add Samples"
    }].filter(Boolean)
  }, /*#__PURE__*/React.createElement(Stepper, {
    activeStep: activeStep
  }, /*#__PURE__*/React.createElement(Step, null, /*#__PURE__*/React.createElement(StepLabel, null, "Directory to Upload To")), /*#__PURE__*/React.createElement(Step, null, /*#__PURE__*/React.createElement(StepLabel, null, "Upload Files"))), activeStep === 0 && /*#__PURE__*/React.createElement(React.Fragment, null, 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,
    canCreateNew: true,
    options: options || [],
    onChangePath: function onChangePath(newS3Path) {
      setS3Path(newS3Path);
      setOptions({
        optionsLoading: true
      });
    }
  })), activeStep === 1 && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Box, {
    display: "flex",
    alignItems: "center"
  }, /*#__PURE__*/React.createElement(IconButton, {
    onClick: function onClick() {
      return setActiveStep(0);
    }
  }, /*#__PURE__*/React.createElement(BackIcon, null)), /*#__PURE__*/React.createElement(SelectedPath, null, "Uploading to: ", s3Path)), /*#__PURE__*/React.createElement(Box, null, /*#__PURE__*/React.createElement(MultiFileDrop, {
    loadFile: /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(file) {
        var filePath, _parseS3URI, bucket, path;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                filePath = s3Path + file.name;
                _context2.next = 3;
                return putBucketItem(filePath, file);

              case 3:
                _parseS3URI = parseS3URI(filePath), bucket = _parseS3URI.bucket, path = _parseS3URI.path;
                uploadedPaths.current.push("https://s3.amazonaws.com/".concat(bucket, "/").concat(path));

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

      return function (_x) {
        return _ref2.apply(this, arguments);
      };
    }(),
    onComplete: function onComplete() {
      setComplete(true);
    }
  }))));
};
export default UploadToS3Dialog;