"use strict";

exports.__esModule = true;
exports.default = useFormSmart;

var _react = require("react");

var _utils = require("../utils");

function isEmpty(val) {
  if ((0, _utils.isObject)(val)) {
    return JSON.stringify(val) === '{}';
  }

  return true;
}

function useFormSmart(option) {
  if (option === void 0) {
    option = {};
  }

  var _option = option,
      value = _option.value,
      sync = _option.sync;
  var ref = (0, _react.useRef)(null);

  var _useState = (0, _react.useState)(false),
      once = _useState[0],
      setOnce = _useState[1];

  var set = (0, _react.useCallback)(function (values) {
    var _ref$current;

    ref == null ? void 0 : (_ref$current = ref.current) == null ? void 0 : _ref$current.setFieldsValue(values);
  }, []);
  var get = (0, _react.useCallback)(function (name) {
    var _ref$current2;

    return ref == null ? void 0 : (_ref$current2 = ref.current) == null ? void 0 : _ref$current2.getFieldValue(name);
  }, []);
  var submit = (0, _react.useCallback)(function () {
    var _ref$current3;

    ref == null ? void 0 : (_ref$current3 = ref.current) == null ? void 0 : _ref$current3.submit();
  }, []);
  var clear = (0, _react.useCallback)(function () {
    var _ref$current4;

    ref == null ? void 0 : (_ref$current4 = ref.current) == null ? void 0 : _ref$current4.resetFields();
  }, []);
  var getAll = (0, _react.useCallback)(function () {
    var _ref$current5;

    return ref == null ? void 0 : (_ref$current5 = ref.current) == null ? void 0 : _ref$current5.getFieldsValue();
  }, []);
  (0, _react.useEffect)(function () {
    if (!isEmpty(value)) {
      if (sync) {
        set(value);
      } else if (!once) {
        set(value);
        setOnce(true);
      }
    }
  }, [value]);
  var methods = {
    set: set,
    get: get,
    submit: submit,
    clear: clear,
    getAll: getAll
  };
  return [ref, methods];
}