<template>
  <v-col
    cols="12"
    sm="6"
  >
    <v-text-field
      v-model="data[field]"
      @change="update()"
      color="purple darken-2"
      :rules="rules"
      required
    ></v-text-field>
  </v-col>
</template>

<script lang="ts">
  import {unref, defineComponent, ref, useFetch, watch, onUnmounted, useContext} from '@nuxtjs/composition-api'
  import {Query} from "@vuex-orm/core";
  import {cloneAndFlatten, cloneAndNest} from "~/services/utils/objectProperties";

  export default defineComponent({
    props: {
      query:{
        type: Object as () => Query,
        required: true
      },
      field:{
        type: String,
        required: true
      },
      rules:{
        type: Array,
        required: false
      }
    },
    setup({query, field}){
      const data = ref({})
      const {route} = useContext();

      const { fetch, fetchState } = useFetch(async () => {
        const entry = await query.find(parseInt(route.value.params.id));
        data.value = cloneAndFlatten(entry);
      })

      const update = () => {
        query.update(cloneAndNest(unref(data)))
      }

      /* const unwatch = watch(
        () => root.$store.state.entities.people.data,
        (state, prevState) => {
         unref(data)[field] = state
        }
      )
      onUnmounted(() => {
        unwatch()
      }) */

      return {
        data,
        update
      }
    }
  })
</script>

<style scoped>
</style>
