import { defineStore } from 'pinia'
import { useDataStore } from '@/stores/dataStore'
import { useSiteManagementPageStore } from '../stores/siteManagementPageStore'
import { useSiteManagementPageValidationStore } from '../validation/siteManagementPageValidationStore'
import { useToastStore } from '@/components/global/toastStore'
import { useUsersStore } from '@/stores/usersStore'
import router from '@/router'

export const useSiteManagementPageService = defineStore(
  'siteManagementPageService',
  () => {
    const dataStore = useDataStore()
    const siteManagementPageStore = useSiteManagementPageStore()
    const siteManagementPageValidationStore = useSiteManagementPageValidationStore()
    const toastStore = useToastStore()
    const usersStore = useUsersStore()

    const GetAllPages = async () => {
      if (siteManagementPageStore.allPagesList.length === 0) {
        let data: Record<string, any> | any = await dataStore.dataGet(
          'Page/?pageNumber=0'
        )

        if (data !== 'errorfalse') {
          siteManagementPageStore.allPagesList = data
        }
      }
    }

    const GetData = async () => {
      siteManagementPageStore.loaded = false

      let data = await dataStore.dataGet('Page/' + siteManagementPageStore.selectedPage)

      if (data !== 'errorfalse') {
        Object.assign(siteManagementPageStore.pageForm, data)
        Object.assign(siteManagementPageStore.pageSafeForm, data)

        setTimeout(() => {
          siteManagementPageStore.loaded = true
        }, 30)
        setTimeout(() => {
          siteManagementPageStore.formChanged = false
        }, 50)
      }
    }

    const SaveData = async () => {
      if (siteManagementPageValidationStore.FormCheck()) {
        let res: any

        if (siteManagementPageStore.isNew) {
          res = await dataStore.dataPost('Page', {
            data: siteManagementPageStore.pageForm
          })
        } else {
          siteManagementPageStore.pageForm.appUserId = usersStore.userId
          res = await dataStore.dataPut('Page/' + siteManagementPageStore.pageForm.id, {
            data: siteManagementPageStore.pageForm
          })
        }

        if (res !== 'errorfalse') {
          if (siteManagementPageStore.isNew)
            toastStore.AddToast('Sayfa başarıyla kaydedildi', 'success', 5000)
          else toastStore.AddToast('Başarıyla kaydedildi', 'success', 5000)

          siteManagementPageStore.formChanged = false
          siteManagementPageStore.loaded = false
          dataStore.pageDataUpdate = true
          if (!siteManagementPageStore.isNew) GetData()
          else router.push('/site-yonetimi/sayfa-listesi')

          siteManagementPageStore.isNew = false
        }
      } else {
        siteManagementPageValidationStore.isFormValid = true
      }
    }

    return { GetAllPages, GetData, SaveData }
  }
)
