import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useEffect, useState } from "react";
import SimpleDialog from "../SimpleDialog";
import DataTable from "react-data-table-component";
import Radio from "@material-ui/core/Radio";
import isEmpty from "lodash/isEmpty";
import datasetManagerCognito from "udt-dataset-managers/dist/CognitoDatasetManager";
import useAuth from "../../utils/auth-handlers/use-auth";
var tableStyle = {
  marginLeft: "auto",
  marginRight: "auto",
  width: "100%"
};
var expandedAnnotationsColumns = [{
  name: "Annotations",
  selector: "annotation"
}, {
  name: "Last Modified",
  selector: "lastModified",
  sortable: true
}];
var columns = [{
  name: "Projects",
  selector: "folder",
  sortable: true
}];
var customStyles = {
  headCells: {
    style: {
      paddingLeft: "10px",
      "font-weight": "bold"
    }
  },
  cells: {
    style: {
      paddingLeft: "25px"
    }
  }
};

var ExpandedRow = function ExpandedRow(_ref) {
  var data = _ref.data;
  var rowAnnotations = data.rowAnnotations;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataTable, {
    style: {
      boxSizing: "border-box",
      paddingLeft: "50px",
      paddingRight: "10px"
    },
    dense: true,
    striped: true,
    noHeader: true,
    columns: expandedAnnotationsColumns,
    data: rowAnnotations,
    noDataComponent: "Make sure the project has \"samples\" folder",
    pagination: rowAnnotations.length > 10,
    paginationPerPage: 10,
    paginationRowsPerPageOptions: [10, 20, 25, 50, 100, 200],
    customStyles: customStyles
  }));
};

export default (function (_ref2) {
  var open = _ref2.open,
      onClose = _ref2.onClose,
      onAddSamples = _ref2.onAddSamples;

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

  var _useAuth = useAuth(),
      authConfig = _useAuth.authConfig;

  var _useState3 = useState(null),
      _useState4 = _slicedToArray(_useState3, 2),
      projects = _useState4[0],
      setProjects = _useState4[1];

  var _useState5 = useState(""),
      _useState6 = _slicedToArray(_useState5, 2),
      projectToFetch = _useState6[0],
      setProjectToFetch = _useState6[1];

  var handleRowSelected = function handleRowSelected(whatsChanging) {
    if (!isEmpty(whatsChanging.selectedRows[0])) {
      setProjectToFetch(whatsChanging.selectedRows[0]);
      setProjects(function (prevState) {
        return prevState.map(function (row) {
          if (whatsChanging.selectedRows[0].id === row.id) {
            row.isSelected = true;
          } else {
            row.isSelected = false;
          }

          return row;
        });
      });
    } else {
      setProjectToFetch(null);
    }
  };

  var getProjects = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var dataFolder, data;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (open) {
                _context2.next = 2;
                break;
              }

              return _context2.abrupt("return");

            case 2:
              if (dm) {
                _context2.next = 4;
                break;
              }

              return _context2.abrupt("return");

            case 4:
              _context2.next = 6;
              return dm.isReady();

            case 6:
              if (_context2.sent) {
                _context2.next = 8;
                break;
              }

              return _context2.abrupt("return");

            case 8:
              _context2.t0 = Array;
              _context2.next = 11;
              return dm.getProjects();

            case 11:
              _context2.t1 = _context2.sent;
              dataFolder = _context2.t0.from.call(_context2.t0, _context2.t1);
              _context2.next = 15;
              return Promise.all(dataFolder.map( /*#__PURE__*/function () {
                var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(obj, index) {
                  var folder, rowAnnotationsContent;
                  return _regeneratorRuntime.wrap(function _callee$(_context) {
                    while (1) {
                      switch (_context.prev = _context.next) {
                        case 0:
                          folder = obj;
                          _context.next = 3;
                          return dm.getListSamples({
                            projectName: obj
                          });

                        case 3:
                          rowAnnotationsContent = _context.sent;
                          return _context.abrupt("return", {
                            id: "".concat(index),
                            folder: folder,
                            rowAnnotations: rowAnnotationsContent.map(function (obj) {
                              return {
                                annotation: obj.split("/samples/")[1]
                              };
                            }),
                            rowAnnotationsUrl: rowAnnotationsContent,
                            isSelected: false
                          });

                        case 5:
                        case "end":
                          return _context.stop();
                      }
                    }
                  }, _callee);
                }));

                return function (_x, _x2) {
                  return _ref4.apply(this, arguments);
                };
              }()));

            case 15:
              data = _context2.sent;
              setProjects(data);

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

    return function getProjects() {
      return _ref3.apply(this, arguments);
    };
  }();

  var setProject = /*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              if (open) {
                _context3.next = 2;
                break;
              }

              return _context3.abrupt("return");

            case 2:
              if (dm) {
                _context3.next = 4;
                break;
              }

              return _context3.abrupt("return");

            case 4:
              _context3.next = 6;
              return dm.isReady();

            case 6:
              if (_context3.sent) {
                _context3.next = 8;
                break;
              }

              return _context3.abrupt("return");

            case 8:
              dm.setProject(projectToFetch.folder);

            case 9:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

    return function setProject() {
      return _ref5.apply(this, arguments);
    };
  }();

  useEffect(function () {
    if (!open) return;
    if (!authConfig) return;
    if (!dm) setDm(new datasetManagerCognito({
      authConfig: authConfig
    }));
  }, [open, authConfig, dm]);
  useEffect(function () {
    getProjects(); // eslint-disable-next-line
  }, [dm]);
  useEffect(function () {
    setProject(); // eslint-disable-next-line
  }, [projectToFetch]);

  var handleAddSample = /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
      var jsons;
      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              if (projectToFetch) {
                _context4.next = 2;
                break;
              }

              return _context4.abrupt("return");

            case 2:
              _context4.next = 4;
              return dm.readJSONAllSample(projectToFetch.rowAnnotationsUrl);

            case 4:
              jsons = _context4.sent;
              onAddSamples(jsons);

            case 6:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));

    return function handleAddSample() {
      return _ref6.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/React.createElement(SimpleDialog, {
    title: "Select Project",
    open: open,
    onClose: onClose,
    actions: [{
      text: "Take sample from project",
      onClick: function onClick() {
        handleAddSample();
      }
    }]
  }, /*#__PURE__*/React.createElement("table", {
    style: tableStyle
  }, /*#__PURE__*/React.createElement("tbody", null, !isEmpty(projects) && /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("th", null, /*#__PURE__*/React.createElement(DataTable, {
    expandableRows: true,
    expandableRowsComponent: /*#__PURE__*/React.createElement(ExpandedRow, null),
    selectableRows: true,
    selectableRowsHighlight: true,
    selectableRowsNoSelectAll: true,
    selectableRowsComponent: Radio,
    dense: true,
    noHeader: true,
    noTableHead: true,
    columns: columns,
    onSelectedRowsChange: handleRowSelected,
    selectableRowSelected: function selectableRowSelected(row) {
      return row.isSelected;
    },
    data: projects,
    pagination: projects.length > 10,
    paginationPerPage: 10,
    paginationRowsPerPageOptions: [10, 20, 25, 50, 100, 200]
  }))))));
});