import { onMounted, ref } from "vue";

export default function useFormErrorMessage(scheme) {
  const formErrorMsg = ref({});

  onMounted(() => {
    // formErrorMsg.value = scheme
    if (scheme && scheme.fields) {
      formErrorMsg.value = Object.fromEntries(
        Object.keys(scheme.fields).map((f) => [f, ""])
      );
    }
  });

  const handleSubmit = (scheme, value) => {
    return new Promise((resolve, reject) => {
      scheme
        .validate(value, {
          abortEarly: false,
        })
        .then((res) => resolve(res))
        .catch((err) => {
          let errorMsg = Object.fromEntries(
            err.inner.map((e) => [e.path, e.message])
          );
          formErrorMsg.value = errorMsg;
          reject(errorMsg);
        });
    });
  };

  const handleErrorReset = () => {
    // formErrorMsg.value = Object.fromEntries(
    //   Object.keys(scheme.fields).map((f) => [f, ""])
    // );
    let resetMsg = {};
    for (let key in formErrorMsg.value) {
      resetMsg[key] = "";
    }
    formErrorMsg.value = resetMsg;
  };

  const updateScheme = (scheme) => {
    if (scheme && scheme.fields) {
      formErrorMsg.value = Object.fromEntries(
        Object.keys(scheme.fields).map((f) => [f, ""])
      );
    }
  };

  return { formErrorMsg, handleSubmit, handleErrorReset, updateScheme };
}
