"use strict";

exports.__esModule = true;
exports.default = exports.useDynamicEditState = exports.useEditState = void 0;

var _react = require("react");

var _reactRedux = require("react-redux");

var _navigation = require("./../selectors/navigation");

var _useDispatchWithModulesData = require("./../hooks/useDispatchWithModulesData");

var _view = require("./../actions/view");

var _modelValidationHelper = require("../utils/modelValidationHelper");

var _useSelectorAndUnwrap = require("./useSelectorAndUnwrap");

var _lodash = require("lodash");

var _mapHelper = require("../utils/mapHelper");

(function () {
  var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined;
  enterModule && enterModule(module);
})();

(function () {
  var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined;
  enterModule && enterModule(module);
})();

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {
  return a;
};

var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) {
  return a;
};

// if you need to override default validation rules just pass new rules with default keys
// as properties of extendedValidationRules
var useEditState = function useEditState(entityId, sectionName, extendedValidationRules) {
  if (extendedValidationRules === void 0) {
    extendedValidationRules = {};
  }

  var currentModuleName = (0, _reactRedux.useSelector)(_navigation.selectCurrentModuleName);
  var dispatchWithModulesData = (0, _useDispatchWithModulesData.useDispatchWithModulesData)();

  var mergedValidationRules = _objectSpread(_objectSpread({}, _modelValidationHelper.validationRules), extendedValidationRules);

  var useFieldState = function useFieldState(keys, initialValue, errorTypes, saveInitialValueToEditState, preValidateInitialValue, fieldDependencies) {
    if (initialValue === void 0) {
      initialValue = "";
    }

    if (errorTypes === void 0) {
      errorTypes = [];
    }

    if (saveInitialValueToEditState === void 0) {
      saveInitialValueToEditState = false;
    }

    if (preValidateInitialValue === void 0) {
      preValidateInitialValue = false;
    }

    if (fieldDependencies === void 0) {
      fieldDependencies = {};
    }

    var stateValue = (0, _useSelectorAndUnwrap.useSelectorAndUnwrap)(function (state) {
      return state.getIn(["view", "edit", currentModuleName, entityId, sectionName, "model"].concat(keys));
    });
    var editState = stateValue || {
      value: initialValue
    };
    var isEditStateValid = (0, _react.useCallback)(function (value, dependencies) {
      if (dependencies === void 0) {
        dependencies = {};
      }

      var valueToValidate = value != null ? value : editState.value;
      var hasAnyValidationErrors = false;
      errorTypes.forEach(function (errorType) {
        var isValid = mergedValidationRules[errorType](valueToValidate, _objectSpread(_objectSpread({}, fieldDependencies), dependencies));

        if (isValid === false && hasAnyValidationErrors === false) {
          dispatchWithModulesData(_view.setEditModelFieldError, [keys, errorType, entityId, sectionName]);
          hasAnyValidationErrors = true;
        }
      });
      return !hasAnyValidationErrors;
    }, [editState.value, fieldDependencies, errorTypes, keys]);
    (0, _react.useEffect)(function () {
      if (saveInitialValueToEditState && stateValue == null) {
        dispatchWithModulesData(_view.setEditModelField, [keys, initialValue, initialValue, entityId, sectionName]);

        if (preValidateInitialValue) {
          isEditStateValid(initialValue);
        }
      }
    }, [initialValue, keys, saveInitialValueToEditState, preValidateInitialValue, stateValue, isEditStateValid]);

    var updateEditState = function updateEditState(newValue, dependencies) {
      dispatchWithModulesData(_view.setEditModelField, [keys, newValue, initialValue, entityId, sectionName]);
      isEditStateValid(newValue, dependencies);
    };

    var resetEditState = function resetEditState() {
      dispatchWithModulesData(_view.setEditModelField, [keys, initialValue, initialValue, entityId, sectionName]);
    };

    return {
      state: editState,
      update: updateEditState,
      reset: resetEditState,
      isValid: isEditStateValid
    };
  };

  __signature__(useFieldState, "useSelectorAndUnwrap{stateValue}\nuseCallback{isEditStateValid}\nuseEffect{}", function () {
    return [_useSelectorAndUnwrap.useSelectorAndUnwrap];
  });

  __signature__(useFieldState, "useSelectorAndUnwrap{stateValue}\nuseCallback{isEditStateValid}\nuseEffect{}", function () {
    return [_useSelectorAndUnwrap.useSelectorAndUnwrap];
  });

  return useFieldState;
}; // if you need to override default validation rules just pass new rules with default keys
// as properties of extendedValidationRules


exports.useEditState = useEditState;

__signature__(useEditState, "useSelector{currentModuleName}\nuseDispatchWithModulesData{dispatchWithModulesData}", function () {
  return [_reactRedux.useSelector, _useDispatchWithModulesData.useDispatchWithModulesData];
});

__signature__(useEditState, "useSelector{currentModuleName}\nuseDispatchWithModulesData{dispatchWithModulesData}", function () {
  return [_reactRedux.useSelector, _useDispatchWithModulesData.useDispatchWithModulesData];
});

var useDynamicEditState = function useDynamicEditState(entityId, sectionName, extendedValidationRules) {
  if (extendedValidationRules === void 0) {
    extendedValidationRules = {};
  }

  var currentModuleName = (0, _reactRedux.useSelector)(_navigation.selectCurrentModuleName);
  var dispatchWithModulesData = (0, _useDispatchWithModulesData.useDispatchWithModulesData)();

  var mergedValidationRules = _objectSpread(_objectSpread({}, _modelValidationHelper.validationRules), extendedValidationRules);

  var useFieldState = function useFieldState(keys, initialValue, saveInitialValueToEditState) {
    if (initialValue === void 0) {
      initialValue = "";
    }

    if (saveInitialValueToEditState === void 0) {
      saveInitialValueToEditState = false;
    }

    var stateValue = (0, _useSelectorAndUnwrap.useSelectorAndUnwrap)(function (state) {
      return state.getIn(["view", "edit", currentModuleName, entityId, sectionName, "model"].concat(keys));
    });
    (0, _react.useEffect)(function () {
      if (saveInitialValueToEditState && stateValue == null) {
        dispatchWithModulesData(_view.setEditModelField, [keys, initialValue, initialValue, entityId, sectionName]);
      }
    }, [initialValue, keys, saveInitialValueToEditState, stateValue]);

    var getEditStateValue = function getEditStateValue(path) {
      var _stateValue$value;

      if (path === void 0) {
        path = [];
      }

      var keyPath = path.join(".");
      var value = (_stateValue$value = stateValue == null ? void 0 : stateValue.value) != null ? _stateValue$value : initialValue;
      var resultValue = (0, _mapHelper.mapModifiedData)(value);
      var result = !path.length ? resultValue : (0, _lodash.get)(resultValue, keyPath, resultValue);
      return result;
    };

    var getValidPath = function getValidPath(path) {
      var _stateValue$value2;

      var result = [];
      var value = (_stateValue$value2 = stateValue == null ? void 0 : stateValue.value) != null ? _stateValue$value2 : initialValue;

      var checkPath = function checkPath(obj) {
        if ((0, _lodash.has)(obj, "value")) {
          result.push("value");
          return obj.value;
        }

        return obj;
      };

      var valueItem = (0, _lodash.cloneDeep)(value);

      for (var i = 0; i < path.length; i++) {
        result.push(path[i]);

        if (i !== path.length - 1) {
          valueItem = checkPath(valueItem[path[i]]);
        }
      }

      return result;
    };

    var hasAnyValidationErrors = function hasAnyValidationErrors(value, path, errorTypes, dependencies) {
      for (var i = 0; i < errorTypes.length; i++) {
        var errorType = errorTypes[i];
        var isValid = mergedValidationRules[errorType](value, dependencies);

        if (isValid === false) {
          dispatchWithModulesData(_view.setEditModelFieldError, [path, errorType, entityId, sectionName]);
          return true;
        } else {
          dispatchWithModulesData(_view.removeEditModelFieldError, [path, entityId, sectionName]);
        }
      }

      return false;
    };

    var updateEditState = function updateEditState(newValue, path, errorTypes, dependencies) {
      if (path === void 0) {
        path = [];
      }

      if (errorTypes === void 0) {
        errorTypes = [];
      }

      if (dependencies === void 0) {
        dependencies = {};
      }

      var pathToField = getValidPath(path);
      var fullPath = !path.length ? [].concat(keys) : [].concat(keys, ["value"], pathToField);
      var initialFieldValue = !path.length ? initialValue : (0, _lodash.get)(initialValue, pathToField);
      dispatchWithModulesData(_view.setEditModelField, [fullPath, newValue, initialFieldValue, entityId, sectionName]);
      hasAnyValidationErrors(newValue, fullPath, errorTypes, dependencies);
    };

    var deleteEditState = function deleteEditState(path) {
      if (path === void 0) {
        path = [];
      }

      var fullPath = !path.length ? [].concat(keys) : [].concat(keys, ["value"], getValidPath(path));

      if (path.length === 0) {
        dispatchWithModulesData(_view.removeEditModel, [fullPath, entityId, sectionName]);
        return;
      }

      if (path.length > 1) {
        path.pop();
        var keyPath = path.join(".");
        return dispatchWithModulesData(_view.removeEditModelField, [fullPath, (0, _lodash.get)(initialValue, keyPath), entityId, sectionName]);
      }

      dispatchWithModulesData(_view.removeEditModelField, [fullPath, initialValue, entityId, sectionName]);
    };

    var resetEditState = function resetEditState(path) {
      if (path === void 0) {
        path = [];
      }

      var fullPath = !path.length ? [].concat(keys) : [].concat(keys, ["value"], getValidPath(path));
      dispatchWithModulesData(_view.setEditModelField, [fullPath, initialValue, initialValue, entityId, sectionName]);
    };

    var isEditStateValid = function isEditStateValid(value, path, errorTypes, dependencies) {
      var _stateValue$value3;

      if (path === void 0) {
        path = [];
      }

      if (errorTypes === void 0) {
        errorTypes = [];
      }

      if (dependencies === void 0) {
        dependencies = {};
      }

      var pathToField = getValidPath(path);
      var fullValue = value != null ? value : (0, _lodash.get)((_stateValue$value3 = stateValue == null ? void 0 : stateValue.value) != null ? _stateValue$value3 : initialValue, pathToField);
      var fullPath = !path.length ? [].concat(keys) : [].concat(keys, ["value"], pathToField);

      if (fullValue != null && (typeof fullValue !== "object" || Array.isArray(fullValue))) {
        dispatchWithModulesData(_view.setEditModelField, [fullPath, fullValue, fullValue, entityId, sectionName]);
      }

      var valueToValidate = value != null ? value : getEditStateValue(path);
      var hasValidationErrors = hasAnyValidationErrors(valueToValidate, fullPath, errorTypes, dependencies);
      return !hasValidationErrors;
    };

    var getError = function getError(path) {
      var _stateValue$value4;

      if (path === void 0) {
        path = [];
      }

      var validPath = getValidPath(path);
      var keyPath = validPath.join(".");
      if (!path.length && (0, _lodash.has)(stateValue, "error")) return stateValue.error;
      var value = (_stateValue$value4 = stateValue == null ? void 0 : stateValue.value) != null ? _stateValue$value4 : initialValue;
      var result = !path.length ? value : (0, _lodash.get)(value, keyPath);
      return result == null ? void 0 : result.error;
    };

    var getEditState = function getEditState(path) {
      var _stateValue$value5;

      if (path === void 0) {
        path = [];
      }

      var keyPath = path.join(".");
      var value = (_stateValue$value5 = stateValue == null ? void 0 : stateValue.value) != null ? _stateValue$value5 : initialValue;
      return !path.length ? value : (0, _lodash.get)(value, keyPath);
    };

    return {
      getStateValue: getEditStateValue,
      update: updateEditState,
      reset: resetEditState,
      isValid: isEditStateValid,
      getError: getError,
      delete: deleteEditState,
      getState: getEditState
    };
  };

  __signature__(useFieldState, "useSelectorAndUnwrap{stateValue}\nuseEffect{}", function () {
    return [_useSelectorAndUnwrap.useSelectorAndUnwrap];
  });

  __signature__(useFieldState, "useSelectorAndUnwrap{stateValue}\nuseEffect{}", function () {
    return [_useSelectorAndUnwrap.useSelectorAndUnwrap];
  });

  return useFieldState;
};

exports.useDynamicEditState = useDynamicEditState;

__signature__(useDynamicEditState, "useSelector{currentModuleName}\nuseDispatchWithModulesData{dispatchWithModulesData}", function () {
  return [_reactRedux.useSelector, _useDispatchWithModulesData.useDispatchWithModulesData];
});

__signature__(useDynamicEditState, "useSelector{currentModuleName}\nuseDispatchWithModulesData{dispatchWithModulesData}", function () {
  return [_reactRedux.useSelector, _useDispatchWithModulesData.useDispatchWithModulesData];
});

var _default = useEditState;
var _default2 = _default;
var _default3 = _default2;
exports.default = _default3;
;

(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;

  if (!reactHotLoader) {
    return;
  }

  reactHotLoader.register(useEditState, "useEditState", "/home/vsts/work/1/s/src/hooks/useEditState.js");
  reactHotLoader.register(useDynamicEditState, "useDynamicEditState", "/home/vsts/work/1/s/src/hooks/useEditState.js");
  reactHotLoader.register(_default, "default", "/home/vsts/work/1/s/src/hooks/useEditState.js");
})();

;

(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();

;

(function () {
  var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined;

  if (!reactHotLoader) {
    return;
  }

  reactHotLoader.register(useEditState, "useEditState", "/home/vsts/work/1/s/src/hooks/useEditState.js");
  reactHotLoader.register(useDynamicEditState, "useDynamicEditState", "/home/vsts/work/1/s/src/hooks/useEditState.js");
  reactHotLoader.register(_default2, "default", "/home/vsts/work/1/s/src/hooks/useEditState.js");
})();

;

(function () {
  var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined;
  leaveModule && leaveModule(module);
})();