import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useDataStore } from '@/stores/dataStore'
import { useMuhasebeSettingsStore } from '../store/muhasebeSettingsStore'
import { useMuhasebeSettingsValidationStore } from '../validation/muhasebeSettingsValidationStore'

export const useMuhasebeSettingsService = defineStore('muhasebeSettingsService', () => {
  const dataStore = useDataStore()
  const muhasebeSettingsStore = useMuhasebeSettingsStore()
  const muhasebeSettingsValidationStore = useMuhasebeSettingsValidationStore()

  const loaded = ref<boolean>(false)

  const SaveMuhasebeSettings = async () => {
    if (muhasebeSettingsValidationStore.FormCheck()) {
      var res: any

      if (muhasebeSettingsStore.isNew) {
        res = await dataStore.dataPost('MuhasebeSettings', {
          data: muhasebeSettingsStore.muhasebeSettingsForm
        })
      } else {
        delete muhasebeSettingsStore.muhasebeSettingsForm.appUser
        res = await dataStore.dataPut(
          'MuhasebeSettings/' + muhasebeSettingsStore.muhasebeSettingsForm.id,
          {
            data: muhasebeSettingsStore.muhasebeSettingsForm
          }
        )
      }

      if (res !== 'errorfalse') {
        muhasebeSettingsStore.isNew = false
        muhasebeSettingsValidationStore.formChanged = false
        muhasebeSettingsStore.muhasebeSettingsLoaded = false
        await GetMuhasebeSettings()
      }
    } else {
      muhasebeSettingsValidationStore.isFormValid = true
    }
  }

  const GetMuhasebeSettings = async () => {
    if (!muhasebeSettingsStore.muhasebeSettingsLoaded) {
      let data = await dataStore.dataGet('MuhasebeSettings')
      if (data !== 'errorfalse') {
        if (data.length === 0) {
          muhasebeSettingsStore.ResetForm()
          muhasebeSettingsStore.isNew = true
        } else {
          muhasebeSettingsStore.isNew = false
          muhasebeSettingsStore.muhasebeSettingsForm = data[0]
          muhasebeSettingsStore.SafeServerData()
        }
      }
    }
  }

  return {
    loaded,
    SaveMuhasebeSettings,
    GetMuhasebeSettings
  }
})
