import { type Ref, computed, defineComponent, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { useVuelidate } from '@vuelidate/core';

import UtenteAppService from '@/entities/utente-app/utente-app.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { type IMessaggio, Messaggio } from '@/shared/model/messaggio.model';
import { type IUtenteApp } from '@/shared/model/utente-app.model';

import MessaggioService from './messaggio.service';

export default defineComponent({
  name: 'MessaggioUpdate',
  setup() {
    const messaggioService = inject('messaggioService', () => new MessaggioService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const messaggio: Ref<IMessaggio> = ref(new Messaggio());

    const utenteAppService = inject('utenteAppService', () => new UtenteAppService());

    const utenteApps: Ref<IUtenteApp[]> = ref([]);
    const isSaving = ref(false);
    const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'it'), true);

    const route = useRoute();
    const router = useRouter();

    const previousState = () => router.go(-1);

    const retrieveMessaggio = async messaggioId => {
      try {
        const res = await messaggioService().find(messaggioId);
        res.spedito = new Date(res.spedito);
        res.letto = new Date(res.letto);
        messaggio.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.messaggioId) {
      retrieveMessaggio(route.params.messaggioId);
    }

    const initRelationships = () => {
      utenteAppService()
        .retrieve()
        .then(res => {
          utenteApps.value = res.data;
        });
    };

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      spedito: {},
      testo: {},
      letto: {},
      utente: {},
    };
    const v$ = useVuelidate(validationRules, messaggio as any);
    v$.value.$validate();

    return {
      messaggioService,
      alertService,
      messaggio,
      previousState,
      isSaving,
      currentLanguage,
      utenteApps,
      v$,
      ...useDateFormat({ entityRef: messaggio }),
      t$,
    };
  },
  created(): void {},
  methods: {
    save(): void {
      this.isSaving = true;
      if (this.messaggio.id) {
        this.messaggioService()
          .update(this.messaggio)
          .then(param => {
            this.isSaving = false;
            this.previousState();
            this.alertService.showInfo(this.t$('smartbookingApp.messaggio.updated', { param: param.id }));
          })
          .catch(error => {
            this.isSaving = false;
            this.alertService.showHttpError(error.response);
          });
      } else {
        this.messaggioService()
          .create(this.messaggio)
          .then(param => {
            this.isSaving = false;
            this.previousState();
            this.alertService.showSuccess(this.t$('smartbookingApp.messaggio.created', { param: param.id }).toString());
          })
          .catch(error => {
            this.isSaving = false;
            this.alertService.showHttpError(error.response);
          });
      }
    },
  },
});
