<template>
  <LayoutContainer v-if="!fetchState.pending">
    <UiForm :id="id" :model="model" :query="query()">
      <template #form.input="{entry, updateRepository}">
        <v-expansion-panels  focusable multiple :value="[0, 1]">
          <!-- Site internet -->
          <UiExpansionPanel id="web_parameters" icon="fa-desktop">
            <v-container fluid class="container">
              <v-row>
                <v-col cols="12" sm="6">
                  <div>
                    <span>{{ $t('yourWebsiteAddressIs') }} : </span>
                    <span>{{ getCurrentWebsite(entry) || $t('none') }}</span>
                  </div>
                </v-col>

                <v-col cols="12" sm="6" v-if="!organizationProfile.isCmf()">
                  <v-btn
                    color="error"
                    v-if="entry['desactivateOpentalentSiteWeb'] === false"
                    @click="confirmWebsiteDeactivation()"
                  >{{ $t('desactivateOpentalentSiteWeb') }} </v-btn>

                  <v-btn
                    color="primary"
                    v-else
                    @click="reactivateOpentalentSiteWeb()"
                  >{{ $t('reactivateOpentalentSiteWeb') }}</v-btn>

                  <lazy-LayoutDialog
                    :show="showSiteWebConfirmationDialog"
                  >
                    <template #dialogTitle>{{ $t('please_confirm')}}</template>
                    <template #dialogText>
                      <div class="ma-2">
                        {{ $t('areYourSureYouWantToDisableYourOpentalentWebsite')}} ?
                      </div>
                    </template>
                    <template #dialogBtn>
                      <v-btn
                        color="ot_super_light_grey"
                        @click="showSiteWebConfirmationDialog=false"
                      >
                        {{ $t('cancel') }}
                      </v-btn>
                      <v-btn
                        color="primary"
                        @click="showSiteWebConfirmationDialog=false;desactivateOpentalentSiteWeb()"
                      >
                        {{ $t('yes') }}
                      </v-btn>
                    </template>
                  </lazy-LayoutDialog>
                </v-col>

                <v-col
                  cols="12"
                  sm="6"
                  v-if="entry['desactivateOpentalentSiteWeb'] === false"
                >
                  <FormParametersSubdomains></FormParametersSubdomains>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="otherWebsite" :data="entry['otherWebsite']" @update="updateRepository" />
                </v-col>

                <v-col cols="12" sm="6" v-if="entry['desactivateOpentalentSiteWeb'] === false">
                  <UiInputAutocompleteWithAPI
                    field="publicationDirectors"
                    label="publicationDirectors"
                    :multiple="true"
                    chips
                    :remote-uri="entry['publicationDirectors']"
                    remote-url="api/access_people"
                    :item-text="['person.givenName', 'person.name']"
                    :searchFunction="accessSearch"
                    @update="updateRepository($event.map((id) => `/api/accesses/${id}`), 'publicationDirectors')"
                  />
                </v-col>

              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- Sms -->
          <UiExpansionPanel id="sms" icon="fa-mobile" v-if="organizationProfile.hasModule(['Sms'])">
            <v-container fluid class="container">
              <v-row>

                <v-col cols="12" sm="6">
                  <UiInputText field="smsSenderName" :data="entry['smsSenderName']" @update="updateRepository" :rules="rules().smsSenderNameRules"  />
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="usernameSMS" :data="entry['usernameSMS']" @update="updateRepository" />
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="passwordSMS" :data="entry['passwordSMS']" @update="updateRepository" type="password" />
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

        </v-expansion-panels>
      </template>
    </UiForm>
  </LayoutContainer>
</template>

<script lang="ts">
import {computed, ComputedRef, defineComponent, reactive, ref, Ref, useContext} from '@nuxtjs/composition-api'
import {useDataUtils} from "~/composables/data/useDataUtils";
import {Parameters} from "~/models/Organization/Parameters";
import {$organizationProfile} from "~/services/profile/organizationProfile";
import {useAccessesProvider} from "~/composables/data/useAccessesProvider";
import {repositoryHelper} from "~/services/store/repository";
import {Query} from "@vuex-orm/core";
import UrlBuilder from "~/services/connection/urlBuilder";
import {Subdomain} from "~/models/Organization/Subdomain";
import {AnyJson} from "~/types/interfaces";
import {queryHelper} from "~/services/store/query";

export default defineComponent({
  name: 'communication',
  setup () {
    const {store, $dataProvider, app: {i18n}} = useContext()
    const {getItemToEdit} = useDataUtils($dataProvider)
    const {getPhysicalByFullName: accessSearch} = useAccessesProvider($dataProvider)

    const showSiteWebConfirmationDialog: Ref<boolean> = ref(false);

    const organizationProfile = reactive($organizationProfile(store))

    const id = store.state.profile.organization.parametersId
    const {fetchState} = getItemToEdit(id, Parameters)

    const repository = repositoryHelper.getRepository(Parameters)
    const query: ComputedRef<Query> = computed(() => repository.query())

    const entry: ComputedRef<AnyJson> = computed(() => {
      return queryHelper.getFlattenEntry(query.value, id)
    })

    /**
     * Build the URL of the current website of the organization
     * Anywhere else, you can rely on organizationProfile.getWebsite(), but here this url has to be
     * dynamic.
     *
     * @see https://ressources.opentalent.fr/display/SPEC/Preferences#Preferences-Siteinternet
     *
     * @param parameters
     */
    const getCurrentWebsite = function (parameters: Parameters) {
      if (parameters.desactivateOpentalentSiteWeb) {
        if (parameters.otherWebsite) {
          return UrlBuilder.prependHttps(parameters.otherWebsite)
        }
        return null
      }
      if (parameters.customDomain) {
        return UrlBuilder.prependHttps(parameters.customDomain)
      }
      // A ce niveau, tous les attributs de Parameters qui pourraient influer sur l'url du site ont été testés, les
      // sous-domaines étant gérés sur d'autres écrans dédiés.
      // On peut donc se reposer sur le profil de l'organisation.
      return organizationProfile.getWebsite()
    }

    const confirmWebsiteDeactivation = function () {
      showSiteWebConfirmationDialog.value = true
    }
    const desactivateOpentalentSiteWeb = function() {
      repositoryHelper.updateStoreFromField(Parameters, entry.value, '1', 'desactivateOpentalentSiteWeb')
    }
    const reactivateOpentalentSiteWeb = function() {
      repositoryHelper.updateStoreFromField(Parameters, entry.value, '0', 'desactivateOpentalentSiteWeb')
    }

    return {
      query: () => query.value,
      rules: () => getRules(i18n),
      organizationProfile,
      id,
      fetchState,
      accessSearch,
      model: Parameters,
      getCurrentWebsite,
      confirmWebsiteDeactivation,
      desactivateOpentalentSiteWeb,
      showSiteWebConfirmationDialog,
      reactivateOpentalentSiteWeb,
      UrlBuilder
    }
  }
})

function getRules (i18n: any) {
  return {
    smsSenderNameRules: [
      (smsSenderNameValue: string) => {
        const pattern = /^[a-zA-z\d]+$/
        return pattern.test(smsSenderNameValue) || i18n.t('smsSenderName_error')
      }
    ]
  }
}
</script>
