//
// Хранилище редактора записи
//
import { useRecordsStore } from './storeRecords.js'

export const useRecordEditorStore = Pinia.defineStore('recordEditorStore', () => {
  const isVisibleRecordEditor = Vue.ref(false)
  const resourceIdentifier = Vue.ref({})
  const record = Vue.ref({})
  const tableInfo = Vue.ref({})
  const columns = Vue.ref([])

  const store = useRecordsStore()

  function showRecordEditor(table_id, record_id) {
    resourceIdentifier.value = { type: `data${table_id}`, id: record_id }
    record.value = store.find(resourceIdentifier.value)
    tableInfo.value = store.find('table', table_id)
    columns.value = tableInfo.value.getRelationship('fields')
    isVisibleRecordEditor.value = true
  }

  function hideRecordEditor() {
    isVisibleRecordEditor.value = false
  }

  function persistRecord() {
    store.persist(resourceIdentifier.value).then(() =>  hideRecordEditor())
  }

  return {
    resourceIdentifier,
    record,
    columns,
    tableInfo,
    persistRecord,
    isVisibleRecordEditor,
    showRecordEditor,
    hideRecordEditor,
  }
})
