<!-- Page de création d'un nouveau sous-domaine -->
<template>
  <main>
    <v-skeleton-loader
      v-if="loading"
      type="text"
    />
    <div v-else>
      <LayoutContainer>
        <v-card class="mb-5 mt-4">
          <FormToolbar title="subdomain" icon="fa-at"/>

          <UiForm
            :id="item.id"
            ref="form"
            :model="model"
            :query="query()"
            :submitActions="submitActions"
          >
            <template #form.input="{entry, updateRepository}">
              <v-container fluid class="container">
                <v-row>
                  <v-col cols="12" sm="6">
                    <div>{{ $t('pleaseEnterYourNewSubdomain')}} :</div>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col cols="12" sm="6">
                    <UiInputText
                      field="subdomain"
                      label="subdomain"
                      :data="entry['subdomain']"
                      type="string"
                      :rules="rules()"
                      @change="checkSubdomainHook($event, updateRepository)"
                    />
                  </v-col>
                </v-row>
                <i v-if="validationPending" class="validation_status">{{ $t('validation_ongoing') }}</i>
                <i v-else-if="subdomainAvailable === true" class="validation_status valid">{{ $t('this_subdomain_is_available') }}</i>
              </v-container>
            </template>

            <template #form.button>
              <NuxtLink :to="{ path: '/parameters/communication'}" class="no-decoration">
                <v-btn class="mr-4 ot_light_grey ot_grey--text">
                  {{ $t('back') }}
                </v-btn>
              </NuxtLink>
            </template>
          </UiForm>
        </v-card>
      </LayoutContainer>
    </div>
  </main>
</template>

<script lang="ts">
import {computed, defineComponent, ref, Ref, useContext} from '@nuxtjs/composition-api'
import {useDataUtils} from "~/composables/data/useDataUtils";
import {Subdomain} from "~/models/Organization/Subdomain";
import {Repository as VuexRepository} from "@vuex-orm/core/dist/src/repository/Repository";
import {Model, Query} from "@vuex-orm/core";
import {repositoryHelper} from "~/services/store/repository";
import {useValidator} from "~/composables/form/useValidator";
import {AnyJson} from "~/types/interfaces";
import {SUBMIT_TYPE} from "~/types/enums";

export default defineComponent({
  name: 'NewFormParametersSubdomain',
  setup () {
    const subdomainAvailable: Ref<boolean | null> = ref(null)
    const form: Ref<HTMLCanvasElement | null> = ref(null);
    const validationPending: Ref<boolean> = ref(false)

    const {$dataProvider, store, app:{i18n}} = useContext()
    const repository: VuexRepository<Model> = repositoryHelper.getRepository(Subdomain)
    const query: Query = repository.query()
    const { checkSubdomainAvailability } = useValidator($dataProvider, i18n).useHandleSubdomain()
    const {createItem} = useDataUtils($dataProvider)
    const {create, loading, item} = createItem(store, Subdomain)

    const submitActions = computed(() => {
      let actions:AnyJson = {}
      actions[SUBMIT_TYPE.SAVE_AND_BACK] = { path: `/parameters/communication` }
      return actions
    })

    const checkSubdomainHook = async (subdomain: string | null, updateRepository: any) => {
      subdomainAvailable.value = null
      if (subdomain !== null && subdomain.match(/^[\w\-]{2,60}$/) !== null) {
        validationPending.value = true
        subdomainAvailable.value = await checkSubdomainAvailability(subdomain);
        validationPending.value = false
      }
      updateRepository(subdomain, 'subdomain');
      (form.value as any).validate()
    }

    if(process.client){
      const itemToCreate: Subdomain = new Subdomain()
      create(itemToCreate)
    }

    /** todo Computed properties needs to be returned as functions until nuxt3 : https://github.com/nuxt-community/composition-api/issues/207 **/
    return {
      loading,
      item,
      model: Subdomain,
      query: () => query,
      submitActions,
      form,
      checkSubdomainHook,
      validationPending,
      subdomainAvailable,
      rules: () => [
        (subdomain: string | null) => (subdomain !== null) || i18n.t('please_enter_a_value_for_the_subdomain'),
        (subdomain: string | null) => (subdomain !== null && subdomain.length >= 2 && subdomain.length <=60) || i18n.t('subdomain_need_to_have_0_to_60_cars'),
        (subdomain: string | null) => (subdomain !== null && subdomain.match(/^[\w\-]+$/) !== null) || i18n.t('subdomain_can_not_contain_spaces_or_special_cars'),
        () => (subdomainAvailable.value !== false) || i18n.t('this_subdomain_is_already_in_use')
      ]
    }
  },
  beforeDestroy() {
    repositoryHelper.cleanRepository(Subdomain)
  }
})
</script>

<style scoped>
.validation_status {
  font-size: 13px;
}
.validation_status.valid {
  color: green;
}
</style>
