<template>
  <select-base
    :options="options"
    :loading="loading"
    :disabled="disabled"
    use-input="10"
    v-bind="$attrs"
    option-value="id"
    option-label="shortNameStat"
    v-on="$listeners"
    :multiple="false"
    :emitArray="false"
  />
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import SelectBase from './select-base.vue';
import {
  OrganizationApi,
  ServiceForStats,
  Organization,
} from '@openapi/registry-service';
import sortBy from 'lodash/sortBy';

@Component({
  inheritAttrs: false,
  components: { SelectBase },
})
export default class SelectService extends Vue {
  @Prop({ required: true }) organisation: Organization;

  protected options: ServiceForStats[] | [] = [];
  protected disabled = true;
  protected loading = false;
  protected search = '';

  @Watch('organisation', { immediate: true, deep: true })
  protected async organisationUpdate(organisation: Organization): Promise<void> {
    this.$emit('input', []);

    if (!organisation) {
      this.options = [];
      this.disabled = true;
      this.loading = false;
      return;
    }
    this.loading = true;
    const orgServices = await new OrganizationApi()
      .searchOrganizationForStats([organisation.id])
      .then(
        ({ data }) =>
          data
            .filter((el) => el.services)
            .flatMap((el) => el.services) as ServiceForStats[]
      )
      .catch((error) => {
        console.error(error);
        this.loading = false;
      });
    const table: { [key: string]: boolean } = {};
    this.options = orgServices || [];
    this.options = this.options.filter(
      ({ shortNameStat, targetId }) =>
        shortNameStat &&
        targetId &&
        !table[shortNameStat] &&
        (table[shortNameStat] = true) &&
        !table[targetId] &&
        (table[targetId] = true)
    );
    this.options = sortBy(this.options, (el) =>
      el.fullName?.toLowerCase().trim()
    );
    this.disabled = !this.options?.length;
    this.loading = false;
  }
}
</script>
