import { defineStore } from 'pinia'
import { useDataStore } from '@/stores/dataStore'
import { usePiyangoStore } from '../stores/piyangoStore'
import { usePiyangoYardimAmacliStore } from '../stores/piyangoYardimAmacliStore'
import { usePiyangoYardimAmacliValidationStore } from '../validation/piyangoYardimAmacliValidationStore'

export const usePiyangoYardimAmacliService = defineStore(
  'piyangoYardimAmacliService',
  () => {
    const dataStore = useDataStore()
    const piyangoStore = usePiyangoStore()
    const piyangoYardimAmacliStore = usePiyangoYardimAmacliStore()
    const piyangoYardimAmacliValidationStore = usePiyangoYardimAmacliValidationStore()

    const GetYardimAmacliData = async () => {
      piyangoYardimAmacliStore.loaded = false
      piyangoYardimAmacliStore.EmptyFormData()
      
      let data = await dataStore.dataGet(
        'yardimbilgi/cekilisIdyegoreobje/' + piyangoStore.selectedLottery
      )
      if (data !== 'errorfalse') {
        piyangoYardimAmacliStore.CreateBiletTable()
        Object.assign(piyangoYardimAmacliStore.piyangoYardimAmacliFormData, data)
        Object.assign(
          piyangoYardimAmacliStore.piyangoYardimAmacliServerFormData,
          piyangoYardimAmacliStore.piyangoYardimAmacliFormData
        )
        if (data === '') piyangoYardimAmacliStore.isNew = true
        else piyangoYardimAmacliStore.isNew = false
        setTimeout(() => {
          piyangoYardimAmacliStore.loaded = true
        }, 30)
      }
    }

    const SaveYardimAmacliForm = async () => {
      if (piyangoYardimAmacliValidationStore.FormCheck()) {
        let form: any
        if (piyangoYardimAmacliStore.isNew) {
          form = await dataStore.dataPost('yardimbilgi/', {
            data: piyangoYardimAmacliStore.piyangoYardimAmacliFormData
          })
        } else {
          form = await dataStore.dataPut('yardimbilgi/' + piyangoYardimAmacliStore.piyangoYardimAmacliFormData.id, {
            data: piyangoYardimAmacliStore.piyangoYardimAmacliFormData
          })
        }
        if (form !== 'errorfalse') {
          piyangoYardimAmacliValidationStore.formChanged = false
          piyangoYardimAmacliStore.loaded = false
          GetYardimAmacliData()
        }
      } else {
        piyangoYardimAmacliValidationStore.isFormValid = true
      }
    }
    return { GetYardimAmacliData, SaveYardimAmacliForm }
  }
)
