import { type ComputedRef, defineComponent, inject, type Ref, ref } from 'vue';
<%_ if (enableTranslation) { _%>
import { useI18n } from 'vue-i18n';
<%_ } _%>
import UserManagementService from './user-management.service';
import { useAlertService } from '@/shared/alert/alert.service';

import { useDateFormat } from '@/shared/composables'

export default defineComponent({
  compatConfig: { MODE: 3 },
  name: '<%=jhiPrefixCapitalized%>UserManagementComponent',
  mounted(): void {
    this.loadAll();
  },
  setup() {
    const alertService = inject('alertService', () => useAlertService(), true);
    const { formatDateShort: formatDate } = useDateFormat();
    const userManagementService = inject('userManagementService', () => new UserManagementService(), true);
    const username = inject<ComputedRef<string>>('currentUsername');

    const error = ref('');
    const success = ref('');
<%_ if (!databaseTypeCassandra) { _%>
    const itemsPerPage = ref(20);
    const page = ref(1);
    const previousPage = ref(1);
    const propOrder = ref('id');
    const reverse = ref(false);
<%_ } _%>
    const isLoading = ref(false);
    const removeId: Ref<<%- user.primaryKey.tsType _%>> = ref(null);
    const users: Ref<any[]> = ref([]);
<%_ if (!databaseTypeCassandra) { _%>
    const totalItems = ref(0);
    const queryCount: Ref<number> = ref(null);
<%_ } _%>

    return {
      formatDate,
      userManagementService,
      alertService,
      error,
      success,
<%_ if (!databaseTypeCassandra) { _%>
      itemsPerPage,
      page,
      previousPage,
      propOrder,
      reverse,
<%_ } _%>
      isLoading,
      removeId,
      users,
      username,
<%_ if (!databaseTypeCassandra) { _%>
      totalItems,
      queryCount,
<%_ } _%>
<%_ if (enableTranslation) { _%>
      t$: useI18n().t,
<%_ } _%>
    };
  },
  methods: {
    setActive(user, isActivated): void {
      user.activated = isActivated;
      this.userManagementService
        .update(user)
        .then(() => {
          this.error = null;
          this.success = 'OK';
          this.loadAll();
        })
        .catch(() => {
          this.success = null;
          this.error = 'ERROR';
          user.activated = false;
        });
    },
    loadAll(): void {
      this.isLoading = true;

      this.userManagementService
        .retrieve({
<%_ if (!databaseTypeCassandra) { _%>
          sort: this.sort(),
          page: this.page - 1,
          size: this.itemsPerPage,
<%_ } _%>
        })
        .then(res => {
          this.isLoading = false;
          this.users = res.data;
<%_ if (!databaseTypeCassandra) { _%>
          this.totalItems = Number(res.headers['x-total-count']);
          this.queryCount = this.totalItems;
<%_ } _%>
        })
        .catch(() => {
          this.isLoading = false;
        });
    },
    handleSyncList(): void {
      this.loadAll();
    },
<%_ if (!databaseTypeCassandra) { _%>
    sort(): any {
      const result = [`${this.propOrder},${this.reverse ? 'desc' : 'asc'}`];
      if (this.propOrder !== 'id') {
        result.push('id');
      }
      return result;
    },
    loadPage(page: number): void {
      if (page !== this.previousPage) {
        this.previousPage = page;
        this.transition();
      }
    },
    transition(): void {
      this.loadAll();
    },
    changeOrder(propOrder: string): void {
      this.propOrder = propOrder;
      this.reverse = !this.reverse;
      this.transition();
    },
<%_ } _%>
    deleteUser(): void {
      this.userManagementService
        .remove(this.removeId)
        .then(res => {
<%_
  const headerAlert = `X-${frontendAppName}-alert`.toLowerCase();
  const headerParams = `X-${frontendAppName}-params`.toLowerCase();
_%>
          this.alertService.showInfo(
<%_ if (enableTranslation) { _%>
            this.t$(res.headers['<%=headerAlert%>'].toString(), { param: decodeURIComponent(res.headers['<%=headerParams%>'].replace(/\+/g, ' ')) }),
<%_ } else { _%>
            res.headers['<%=headerAlert%>'].toString(),
<%_ } _%>
            { variant: 'danger' },
          );
          this.removeId = null;
          this.loadAll();
          this.closeDialog();
        })
        .catch(error => {
          this.alertService.showHttpError(error.response);
        });
    },
    prepareRemove(instance): void {
      this.removeId = instance.login;
      if (<any>this.$refs.removeUser) {
        (<any>this.$refs.removeUser).show();
      }
    },
    closeDialog(): void {
      if (<any>this.$refs.removeUser) {
        (<any>this.$refs.removeUser).hide();
      }
    },
  },
});
