<template>
  <main>
    <v-form
      ref="form"
      v-model="properties.valid"
      lazy-validation
      :readonly="readOnly"
    >
      <v-container fluid class="container btnActions">
        <v-row>
          <v-col cols="12" sm="12">
            <slot name="form.button"></slot>
            <v-btn v-if="!readOnly" class="mr-4 ot_green ot_white--text" @click="submit">
              Enregistrer
            </v-btn>
          </v-col>
        </v-row>
      </v-container>

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

      <v-container fluid class="container btnActions">
        <v-row>
          <v-col cols="12" sm="12">
            <slot name="form.button"></slot>
            <v-btn v-if="!readOnly" class="mr-4 ot_green ot_white--text" @click="submit">
              Enregistrer
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-form>

    <div class="text-center">
      <v-dialog
        v-model="dialog"
        width="500"
      >
        <v-card>
          <v-card-title class="text-h5 grey lighten-2">
            Attention
          </v-card-title>

          <v-card-text>
            <br>
            <p>Vous souhaitez quitter ce formulaire sans avoir enregistré</p>
          </v-card-text>

          <v-divider></v-divider>

          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn class="mr-4 submitBtn ot_danger ot_white--text" @click="closeDialogs">
              Retour
            </v-btn>
            <v-btn class="mr-4 submitBtn ot_green ot_white--text" @click="goEvenUnsavedData">
              Continuer
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </div>
  </main>
</template>

<script lang="ts">
  import {defineComponent, reactive, useContext, computed, toRefs, onBeforeUnmount, onBeforeMount} from '@nuxtjs/composition-api'
  import {useRepositoryHelper} from "~/use/store/useRepository";
  import {useQueryHelper} from "~/use/store/useQuery";
  import {Query} from "@vuex-orm/core";
  import {QUERY_TYPE} from "~/types/enums";

  export default defineComponent({
    props: {
      model: {
        type: Function,
        required: true
      },
      id: {
        type: Number,
        required: true
      },
      query: {
        type: Object as () => Query,
        required: true
      },
    },
    setup: function (props) {
      const {$dataPersister, store, app} = useContext()

      const {id, query} = toRefs(props)
      const repository = useRepositoryHelper.getRepository(props.model)
      const properties = reactive({
        valid: false,
        saveOk: false,
        saveKo: false
      })

      const readOnly = computed(() => {
        return false
      })

      const entry = computed(() => {
        return useQueryHelper.getFlattenEntry(query.value, id.value)
      })

      const handler = getEventHandler()

      const updateRepository = (newValue: string, field: string) => {
        addEventListener(handler)
        store.commit('form/setDirty', true)
        useRepositoryHelper.updateStoreFromField(repository, entry.value, newValue, field)
      }

      const dialog = computed(() => {
        return store.state.form.showConfirmToLeave
      })

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

      const goEvenUnsavedData = () => {
        store.commit('form/setDirty', false)
        store.commit('form/setShowConfirmToLeave', false)

        const entryCopy = query.value.first()
        if (entryCopy && entryCopy.$getAttributes()['originalState']) {
          useRepositoryHelper.updateStore(repository, entryCopy.$getAttributes()['originalState'])
        }

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

      onBeforeMount(() => {
        clearEventListener(handler)
      })

      onBeforeUnmount(() => {
        clearEventListener(handler)
      })

      const submit = async () => {
        try {
          store.commit('form/setDirty', false)
          clearEventListener(handler)

          await $dataPersister.invoke({
            type: QUERY_TYPE.MODEL,
            model: props.model,
            id: id.value
          })
        } catch (error) {
          console.log('aie aie aie')
        }
      }

      return {
        submit,
        updateRepository,
        properties,
        readOnly,
        dialog,
        entry,
        goEvenUnsavedData,
        closeDialogs,
      }
    },
    methods: {

      // async submit(){
      //
      //   console.log()
      //
      //
      //   const form:VForm = this.$refs.form;
      //   if(form.validate()){
      //     const model = await this.repository.find(parseInt(this.$route.params.id));
      //     if(model){
      //       const playload = model.$toJson();
      //
      //       this.$http.$put(`https://local.new.api.opentalent.fr/api/${model.$entity}/${this.$route.params.id}`, playload)
      //         .then(()=>{
      //           this.saveOk=true
      //         }, () =>{
      //           this.saveKo=true
      //         })
      //
      //       setTimeout(()=>{
      //         this.saveOk=false
      //         this.saveKo=false
      //       },2000)
      //     }
      //   }
      // }
    }
  })

  function getEventHandler() {
    return function (e: any) {
      // Cancel the event
      e.preventDefault();
      // Chrome requires returnValue to be set
      e.returnValue = '';
    };
  }

  function addEventListener(handler: any) {
    if (process.browser) {
      window.addEventListener('beforeunload', handler);
    }
  }

  function clearEventListener(handler: any) {
    if (process.browser) {
      window.removeEventListener('beforeunload', handler);
    }
  }

</script>

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