import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import useActiveDatasetManager from "../use-active-dataset-manager";
import useEventCallback from "use-event-callback";
import fromUDTCSV from "../../utils/from-udt-csv";
import LocalStorageDatasetManager from "udt-dataset-managers/dist/LocalStorageDatasetManager";
import { useToasts } from "../../components/Toasts";
export default (function () {
  var _useActiveDatasetMana = useActiveDatasetManager(),
      _useActiveDatasetMana2 = _slicedToArray(_useActiveDatasetMana, 2),
      setActiveDatasetManager = _useActiveDatasetMana2[1];

  var _useToasts = useToasts(),
      addToast = _useToasts.addToast;

  return useEventCallback(function (fsFile) {
    var fileName = fsFile.name,
        filePath = fsFile.path;

    function handleLoadedFile(_x) {
      return _handleLoadedFile.apply(this, arguments);
    }

    function _handleLoadedFile() {
      _handleLoadedFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(content) {
        var dataset, dm;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;

                if (fileName.endsWith("csv")) {
                  dataset = fromUDTCSV(content);
                } else {
                  dataset = JSON.parse(content);
                } // TODO validate OHA and prompt to open anyway if invalid


                dm = new LocalStorageDatasetManager();
                _context.next = 5;
                return dm.setDataset(_objectSpread(_objectSpread({}, dataset), {}, {
                  filePath: filePath,
                  name: fileName
                }));

              case 5:
                setActiveDatasetManager(dm);
                _context.next = 12;
                break;

              case 8:
                _context.prev = 8;
                _context.t0 = _context["catch"](0);
                console.log(_context.t0.toString());
                addToast("Couldn't read file, see console for details", "error"); // addError(`Could not read file "${fsFile.name}"`)

              case 12:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[0, 8]]);
      }));
      return _handleLoadedFile.apply(this, arguments);
    }

    if (fsFile.content) {
      handleLoadedFile(fsFile.content);
    } else {
      var reader = new FileReader();

      reader.onload = function (e) {
        var content = e.target.result;
        handleLoadedFile(content);
      };

      reader.readAsText(fsFile);
    }

    setActiveDatasetManager();
  });
});