import { defineComponent, reactive, ref, watch } from 'vue'

import { serv_constants } from '@store/Modules/serv_constants'
import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { useGlobalStore } from '@store/globalStore'
import { useUserStore } from '@store/UserStore'
import { useRouter } from 'vue-router'
import useVuelidate from '@vuelidate/core'
import { validations } from '@src/views/admin/install_site/install_site-validate'
import { tools } from '@tools'

export default defineComponent({
  name: 'install_site',
  setup() {
    const $q = useQuasar()
    const { t } = useI18n()
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const $router = useRouter()

    const emailsent = ref(false)

    const form = reactive({
      idappSent: '',
      email: '',
      name: '',
      host: '',
      code: '',
      username: '',
      password: '',

    })

    const emailRef = ref(null)
    const idapp = ref('')

    const v$ = useVuelidate(validations, form)

    function submit() {
      console.log('submit')

      // @ts-ignore
      emailRef.value!.validate()

      // @ts-ignore
      if (emailRef.value!.hasError) {
        // form has error
        tools.showNotif($q, t('reg.err.errore_generico'))
        return
      }

      $q.loading.show({ message: t('reset.incorso') })

      userStore.addNewSite({ ...form })
        .then((ris: any) => {
          if (ris.code === serv_constants.RIS_CODE_OK) {
            emailsent.value = true
            idapp.value = ris.idapp
            tools.showPositiveNotif($q, t('install.created', { idapp: ris.idapp }))
            console.log('VAI A SIGNIN (2):')
            $router.replace('/signin')
            form.password = ''
          } else
            tools.showNegativeNotif($q, t('reg.err.site_not_created'))
          $q.loading.hide()
        }).catch((err: any) => {
          console.log('ERROR = ' + err.error)
          $q.loading.hide()
        })

    }

    function emailinviata() {
      return emailsent.value
    }

    return {
      globalStore,
      submit,
      tools,
      form,
      v$,
      emailsent,
      emailinviata,
      emailRef,
      idapp,
    }
  },
})
