import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useEffect, useState, useReducer } from "react";
import useActiveDatasetManager from "../use-active-dataset-manager";
export default (function (datasetPropertyKey) {
  var _ref2, _ref4;

  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      propVal = _useState2[0],
      setPropVal = _useState2[1];

  var _useReducer = useReducer(function (state) {
    return state + 1;
  }, 0),
      _useReducer2 = _slicedToArray(_useReducer, 2),
      propVersion = _useReducer2[0],
      incPropVersion = _useReducer2[1];

  var _useActiveDatasetMana = useActiveDatasetManager(),
      _useActiveDatasetMana2 = _slicedToArray(_useActiveDatasetMana, 1),
      dm = _useActiveDatasetMana2[0];

  useEffect(function () {
    if (!dm || !datasetPropertyKey) return;
    dm.on("dataset-property-changed", function (_ref) {
      var key = _ref.key;

      if (key === datasetPropertyKey) {
        incPropVersion();
      }
    });
  }, [dm, datasetPropertyKey]);
  useEffect(function () {
    if (!dm || !datasetPropertyKey) return;
    dm.getDatasetProperty(datasetPropertyKey).then(function (newPropVal) {
      setPropVal(newPropVal);
    });
  }, [dm, propVersion, datasetPropertyKey]); // interface -> updateInterface

  var updateFunctionKeyName = "update".concat(datasetPropertyKey[0].toUpperCase()).concat(datasetPropertyKey.slice(1));
  if (!dm || !datasetPropertyKey) return _ref2 = {}, _defineProperty(_ref2, "".concat(datasetPropertyKey, "Loading"), true), _defineProperty(_ref2, updateFunctionKeyName, function () {
    throw new Error("".concat(datasetPropertyKey, " isn't loaded"));
  }), _ref2;
  return _ref4 = {}, _defineProperty(_ref4, datasetPropertyKey, propVal), _defineProperty(_ref4, updateFunctionKeyName, function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(newPropVal) {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return dm.setDatasetProperty(datasetPropertyKey, newPropVal);

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

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