<!--
Formulaire générique

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

<template>
  <main>
    <v-form
      ref="form"
      lazy-validation
      :readonly="readonly"
    >
      <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>

      <slot name="form.input" v-bind="{entry,updateRepository}"/>

      <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>

    <lazy-LayoutDialog
      :show="showDialog"
    >
      <template v-slot:dialogText>
        <v-card-title class="text-h5 grey lighten-2">
          {{ $t('attention') }}
        </v-card-title>
        <v-card-text>
          <br>
          <p>{{ $t('quit_without_saving_warning') }}</p>
        </v-card-text>
      </template>
      <template v-slot: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>
    </lazy-LayoutDialog>

  </main>
</template>

<script lang="ts">
import {computed, ComputedRef, defineComponent, ref, Ref, toRefs, ToRefs, useContext} from '@nuxtjs/composition-api'
import {Query} from '@vuex-orm/core'
import {repositoryHelper} from '~/services/store/repository'
import {queryHelper} from '~/services/store/query'
import {FORM_STATUS, QUERY_TYPE, SUBMIT_TYPE, TYPE_ALERT} from '~/types/enums'
import {AnyJson} from '~/types/interfaces'
import {$useForm} from '~/use/form/useForm'
import * as _ from 'lodash'
import Form from "~/services/store/form";
import Page from "~/services/store/page";
import UseNextStepFactory from "~/use/form/useNextStepFactory";

export default defineComponent({
  props: {
    model: {
      type: Function,
      required: true
    },
    id: {
      type: [Number, String],
      required: true
    },
    query: {
      type: Object as () => Query,
      required: true
    },
    submitActions: {
      type: Object,
      required: false,
      default: () => {
        let actions:AnyJson = {}
        actions[SUBMIT_TYPE.SAVE] = {}
        return actions
      }
    }
  },
  setup(props) {
    const {$dataPersister, store, app: {router, i18n}} = useContext()
    const {markFormAsDirty, markFormAsNotDirty, readonly} = $useForm()
    const nextStepFactory = new UseNextStepFactory()
    const {id, query}: ToRefs = toRefs(props)
    const page = new Page(store)
    const form:Ref<any> = ref(null)

    const entry: ComputedRef<AnyJson> = computed(() => {
      return queryHelper.getFlattenEntry(query.value, id.value)
    })

    const updateRepository = (newValue: string, field: string) => {
      markFormAsDirty()
      repositoryHelper.updateStoreFromField(props.model, entry.value, newValue, field)
    }

    const submit = async (next: string|null = null) => {
      if(form.value.validate()){
        markFormAsNotDirty()

        try {
          const response = await $dataPersister.invoke({
            type: QUERY_TYPE.MODEL,
            model: props.model,
            id: store.state.form.formStatus === FORM_STATUS.EDIT ? id.value : null,
            idTemp: store.state.form.formStatus === FORM_STATUS.CREATE ? id.value : null,
            query: props.query
          })

          page.addAlerts(TYPE_ALERT.SUCCESS, [i18n.t('saveSuccess') as string])
          nextStep(next, response.data)
        } catch (error) {
          if (error.response.status === 422) {
            if(error.response.data['violations']){
              const violations:Array<string> = []
              const fields:Array<string> = []
              for(const violation of error.response.data['violations']){
                violations.push(i18n.t(violation['message']) as string)
                fields.push(violation['propertyPath'])
              }

              new Form(store).addViolations(fields)
              page.addAlerts(TYPE_ALERT.ALERT, violations)
            }
          }
        }
      }else{
        page.addAlerts(TYPE_ALERT.ALERT, [i18n.t('invalide_form') as string])
      }
    }

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

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

    const closeDialog = () => {
      store.commit('form/setShowConfirmToLeave', false)
    }

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

    const quitForm = () => {
      markFormAsNotDirty()
      store.commit('form/setShowConfirmToLeave', false)

      const entryCopy = query.value.first()
      if (entryCopy && entryCopy.$getAttributes().originalState) {
        repositoryHelper.persist(props.model, entryCopy.$getAttributes().originalState)
      }

      if (router) {
        router.push(store.state.form.goAfterLeave)
      }
    }

    const actions = computed(()=>{
      return _.keys(props.submitActions)
    })

    return {
      form,
      submit,
      updateRepository,
      readonly,
      showDialog,
      entry,
      quitForm,
      closeDialog,
      saveAndQuit,
      actions
    }
  }
})
</script>

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