import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import * as React from 'react';
import connect from './connect';
import { debounce } from 'lodash';
import isEqual from 'react-fast-compare';
var PersistImpl = /*#__PURE__*/function (_React$Component) {
  function PersistImpl() {
    var _this;
    _classCallCheck(this, PersistImpl);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, PersistImpl, [].concat(args));
    _defineProperty(_this, "saveForm", debounce(function (data) {
      if (_this.props.isSessionStorage) {
        window.sessionStorage.setItem(_this.props.name, JSON.stringify(data));
      } else {
        window.localStorage.setItem(_this.props.name, JSON.stringify(data));
      }
    }, _this.props.debounce));
    return _this;
  }
  _inherits(PersistImpl, _React$Component);
  return _createClass(PersistImpl, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (!isEqual(prevProps.formik, this.props.formik)) {
        this.saveForm(this.props.formik);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var maybeState = this.props.isSessionStorage ? window.sessionStorage.getItem(this.props.name) : window.localStorage.getItem(this.props.name);
      if (maybeState && maybeState !== null) {
        this.props.formik.setFormikState(JSON.parse(maybeState));
      }
    }
  }, {
    key: "render",
    value: function render() {
      return null;
    }
  }]);
}(React.Component);
_defineProperty(PersistImpl, "defaultProps", {
  debounce: 300
});
export var FormPersist = connect(PersistImpl);