import {FORM_FUNCTION} from "~/types/enum/enums";
import {defineStore} from "pinia";
import {Ref, ref} from "@vue/reactivity";
import {AnyJson} from "~/types/data";

export const useFormStore = defineStore('form', () => {
  const formFunction: Ref<FORM_FUNCTION> = ref(FORM_FUNCTION.EDIT)
  const violations: Ref<AnyJson> = ref({})
  const readonly: Ref<boolean> = ref(false)
  const dirty: Ref<boolean> = ref(false)
  const showConfirmToLeave: Ref<boolean> = ref(false)
  const goAfterLeave: Ref<string | null> = ref(null)

  const setViolations = (newViolations: Array<string>) => {
    violations.value = newViolations
  }

  const addViolation = (invalidFields: AnyJson) => {
    // TODO: à revoir
    violations.value = invalidFields
  }

  const setReadOnly = (value: boolean) => {
    readonly.value = value
  }

  const setFormFunction = (newFormFunction: FORM_FUNCTION) => {
    formFunction.value = newFormFunction
  }

  const setDirty = (value: boolean) => {
    dirty.value = value
  }

  const setShowConfirmToLeave = (value: boolean) => {
    showConfirmToLeave.value = value
  }

  const setGoAfterLeave = (value: string) => {
    goAfterLeave.value = value
  }

  /**
   * Actions devant être gérées si on souhaite quitter une page
   *
   * @param to
   */
  const handleActionsAfterLeavingPage = (to: any) => {
    if (dirty) {
      showConfirmToLeave.value = true
      goAfterLeave.value = to
    } else {
      formFunction.value = FORM_FUNCTION.EDIT
      violations.value = []
    }
  }

  return {
    formFunction,
    violations,
    readonly,
    dirty,
    showConfirmToLeave,
    goAfterLeave,
    setViolations,
    addViolation,
    setReadOnly,
    setFormFunction,
    setDirty,
    setShowConfirmToLeave,
    setGoAfterLeave,
    handleActionsAfterLeavingPage
  }
})
