<!--
Formulaire générique

@see https://vuetifyjs.com/en/components/forms/#usage
-->

<template>
  <main>
    <v-form
      ref="form"
      lazy-validation
      :readonly="readonly"
      @submit.prevent=""
      @change="onChange"
    >
      <!-- Top action bar -->
      <v-container fluid class="container btnActions">
        <v-row>
          <v-col cols="12" sm="12">
            <slot name="form.button"/>

            <UiButtonSubmit
              v-if="!readonly"
              @submit="submit"
              :actions="actions"
            ></UiButtonSubmit>
          </v-col>
        </v-row>
      </v-container>

      <!-- Content -->
      <slot name="form.input" v-bind="{model, entity}"/>

      <!-- Bottom action bar -->
      <v-container fluid class="container btnActions">
        <v-row>
          <v-col cols="12" sm="12">
            <slot name="form.button"/>

            <UiButtonSubmit
              @submit="submit"
              :actions="actions"
            ></UiButtonSubmit>
          </v-col>
        </v-row>
      </v-container>
    </v-form>

    <!-- Confirmation dialog -->
    <LazyLayoutDialog
      :show="showDialog"
    >
      <template #dialogText>
        <v-card-title class="text-h5 grey lighten-2">
          {{ $t('caution') }}
        </v-card-title>
        <v-card-text>
          <br>
          <p>{{ $t('quit_without_saving_warning') }}</p>
        </v-card-text>
      </template>
      <template #dialogBtn>
        <v-btn class="mr-4 submitBtn ot_green ot_white--text" @click="closeDialog">
          {{ $t('back_to_form') }}
        </v-btn>
        <v-btn class="mr-4 submitBtn ot_green ot_white--text" @click="saveAndQuit">
          {{ $t('save_and_quit') }}
        </v-btn>
        <v-btn class="mr-4 submitBtn ot_danger ot_white--text" @click="quitForm">
          {{ $t('quit_form') }}
        </v-btn>
      </template>
    </LazyLayoutDialog>

  </main>
</template>

<script setup lang="ts">

import {computed, ComputedRef, ref, Ref} from "@vue/reactivity";
import {AnyJson} from "~/types/data";
import {FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT} from "~/types/enums";
import {useNuxtApp, useRouter} from "#app";
import { useFormStore } from "~/store/form";
import {Route} from "@intlify/vue-router-bridge";
import {useEntityManager} from "~/composables/data/useEntityManager";
import ApiModel from "~/models/ApiModel";
import {usePageStore} from "~/store/page";

const props = defineProps({
  model: {
    type: Function as any as () => typeof ApiModel,
    required: true
  },
  entity: {
    type: Object as () => ApiModel,
    required: true
  },
  onChanged: {
    type: Function,
    required: false
  },
  submitActions: {
    type: Object,
    required: false,
    default: () => {
      let actions: AnyJson = {}
      actions[SUBMIT_TYPE.SAVE] = {}
      return actions
    }
  }
})

const { i18n } = useNuxtApp()
const router = useRouter()
const { em } = useEntityManager()

const isValid: Ref<boolean> = ref(true)
const errors: Ref<Array<string>> = ref([])

/**
 * Référence au component v-form
 */
const form: Ref = ref(null)

const readonly: ComputedRef<boolean> = computed(() => {
  return useFormStore().readonly
})

/**
 * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
 *
 * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
 */
const validate = async function () {
  const validation = await form.value.validate()

  isValid.value = validation.valid
  errors.value = validation.errors
}

/**
 * Handle events if the form is dirty to prevent submission
 * @param e
 */
// TODO: voir si encore nécessaire avec le @submit.prevent
const preventSubmit = (e: any) => {
  // Cancel the event
  e.preventDefault()
  // Chrome requires returnValue to be set
  e.returnValue = ''
}

/**
 * Définit l'état dirty (modifié) du formulaire
 */
const setIsDirty = (dirty: boolean) => {
  useFormStore().setDirty(dirty)

  // If dirty, add the preventSubmit event listener
  // TODO: voir si encore nécessaire avec le @submit.prevent
  if (process.browser) {
    if (dirty) {
      window.addEventListener('beforeunload', preventSubmit)
    } else {
      window.removeEventListener('beforeunload', preventSubmit)
    }
  }
}

/**
 *  Update store when form is changed (if valid)
 */
const onFormChange = async () => {
  await validate()

  if (isValid.value) {
    em.save(props.model, props.entity)
    setIsDirty(true)

    if (props.onChanged) {
      // Execute the custom onChange method, if defined
      // TODO: voir quelles variables passer à cette méthode custom ; voir même si cette méthode est utilisée
      props.onChanged()
    }
  }
}


// <--- TODO: revoir
/**
 * Action Sauvegarder qui redirige vers la page d'édition si on est en mode create
 * @param route
 * @param id
 * @param router
 */
function save(route: Route, id: number, router: any){
  if(useFormStore().formFunction === FORM_FUNCTION.CREATE){
    route.path += id
    router.push(route)
  }
}

/**
 * Action sauvegarder et route suivante qui redirige vers une route
 * @param route
 * @param router
 */
function saveAndGoTo(route: Route, router: any){
  router.push(route)
}

/**
 * Factory des fonctions permettant d'assurer l'étape suivant à la soumission d'un formulaire
 *
 * @param args
 * @param response
 * @param router
 */
function nextStepFactory(args: any, response: AnyJson, router: any){
  const factory: AnyJson = {}
  factory[SUBMIT_TYPE.SAVE] = () => save(args, response.id, router)
  factory[SUBMIT_TYPE.SAVE_AND_BACK] = () => saveAndGoTo(args, router)
  return factory
}

const nextStep = (next: string | null, response: AnyJson) => {
  if (next === null)
    return
  nextStepFactory(props.submitActions[next], response, router)[next]()
}

// ---> Fin du todo


/**
 * Soumet le formulaire
 *
 * @param next
 */
const submit = async (next: string|null = null) => {
  await validate()

  if (!isValid.value) {
    usePageStore().addAlerts(TYPE_ALERT.ALERT, ['invalid_form'])
    return
  }

  setIsDirty(false)

  try {
    const updatedEntity = await em.persist(props.model, props.entity)

    usePageStore().addAlerts(TYPE_ALERT.SUCCESS, ['saveSuccess'])

    // nextStep(next, updatedEntity)

  } catch (error: any) {

    if (error.response.status === 422 && error.response.data['violations']) {
        const violations: Array<string> = [] // TODO: cette variable est-elle utile?
        let fields: AnyJson = {}

        for (const violation of error.response.data['violations']) {
          violations.push(i18n.t(violation['message']) as string)
          fields = Object.assign(fields, {[violation['propertyPath']] : violation['message']})
        }

        useFormStore().addViolations(fields)

        usePageStore().addAlerts(TYPE_ALERT.ALERT, ['invalid_form'])
    }
  }
}

const showDialog: ComputedRef<boolean> = computed(() => {
  return useFormStore().showConfirmToLeave
})

const closeDialog = () => {
  useFormStore().setShowConfirmToLeave(false)
}

const saveAndQuit = async () => {
  await submit()
  quitForm()
}

const quitForm = () => {
  setIsDirty(false)

  useFormStore().setShowConfirmToLeave(false)

  em.reset(props.model, props.entity.value)

  if (router) {
    // @ts-ignore
    router.push(useFormStore().goAfterLeave)
  }
}

const actions = computed(()=>{
  return useKeys(props.submitActions)
})
</script>

<style scoped>
.btnActions {
  text-align: right;
}
</style>
