import { ref, computed } from "vue";
import { propsFactory, getCurrentInstance, getCurrentInstanceName } from "../../utils/dist/index.mjs";
const makeValidationProps = propsFactory({
  disabled: Boolean,
  error: Boolean,
  errorMessages: {
    type: [Array, String],
    default: () => []
  },
  maxErrors: {
    type: [Number, String],
    default: 1
  },
  readonly: Boolean,
  rules: {
    type: Array,
    default: () => []
  },
  modelValue: null
});
function useValidation(props, name = getCurrentInstanceName()) {
  const errorMessages = ref([]);
  const isPristine = ref(true);
  const isDisabled = computed(() => !!props.disabled);
  const isReadonly = computed(() => !!props.readonly);
  const isValid = computed(() => {
    var _a;
    if (props.error || ((_a = props.errorMessages) == null ? void 0 : _a.length) || errorMessages.value.length)
      return false;
    return isPristine.value ? null : true;
  });
  const isValidating = ref(false);
  const validationClasses = computed(() => {
    return {
      [`${name}--error`]: isValid.value === false,
      [`${name}--disabled`]: isDisabled.value,
      [`${name}--readonly`]: isReadonly.value
    };
  });
  const vm = getCurrentInstance("useValidation");
  function reset() {
    resetValidation();
    vm == null ? void 0 : vm.emit("update:modelValue", null);
  }
  function resetValidation() {
    isPristine.value = true;
    errorMessages.value = [];
  }
  async function validate() {
    var _a, _b;
    const results = [];
    errorMessages.value = [];
    isValidating.value = true;
    for (const rule of props.rules) {
      if (results.length >= (props.maxErrors || 1)) {
        break;
      }
      const handler = typeof rule === "function" ? rule : () => rule;
      const result = await handler((_b = (_a = props == null ? void 0 : props.modelValue) == null ? void 0 : _a.value) != null ? _b : props.modelValue);
      if (result === true)
        continue;
      if (typeof result !== "string") {
        console.warn(`${result} is not a valid value. Rule functions must return boolean true or a string.`);
        continue;
      }
      results.push(result);
    }
    errorMessages.value = results;
    isValidating.value = false;
    isPristine.value = false;
    return errorMessages.value;
  }
  return {
    errorMessages,
    isDisabled,
    isReadonly,
    isPristine,
    isValid,
    isValidating,
    reset,
    resetValidation,
    validate,
    validationClasses
  };
}
export {
  makeValidationProps,
  useValidation
};
//# sourceMappingURL=index.mjs.map
