<template>
  <div
    class="flex justify-between items-center bg-white q-pa-md rounded-borders"
  >
    <div
      class="column justify-center text-h5 q-mr-auto"
      style="min-height: 36px"
    >
      <div class="text-h6 flex items-center text-grey-9 col q-pr-md">
        <q-btn
          padding="xs"
          class="text-grey-7 q-mr-md"
          color="grey-3"
          icon="arrow_back"
          @click="goBackFunc"
        />
        <span class="text-h5">{{ $t('interagencies.interagency') }}</span>
      </div>
    </div>

    <div class="q-gutter-x-sm">
      <q-btn
        @click="$emit('set-edit-mode', !editMode)"
        unelevated
        color="primary"
        :icon="editMode ? 'visibility' : 'edit'"
      >
        <q-tooltip :delay="500">
          {{ editMode ? $t('base.preview.dialog.title') : $t('base.edit') }}
        </q-tooltip>
      </q-btn>

      <q-btn
        v-if="isChanged"
        @click="saveInteragency"
        :loading="loading"
        unelevated
        color="primary"
        icon="save"
      >
        <q-tooltip :delay="500">{{ $t('base.save') }}</q-tooltip>
      </q-btn>

      <q-btn
        @click="(v) => (isDeleteModalVisible = true)"
        unelevated
        color="primary"
        icon="delete"
      >
        <q-tooltip :delay="500">
          {{ $t('base.delete') }}
        </q-tooltip>
      </q-btn>
    </div>

    <q-dialog class="full-width" v-model="isDeleteModalVisible">
      <q-card class="q-pa-md">
        <ConfirmationForm
          :input-data="{ title: $t('interagencies.message.confirm.delete') }"
          @submit="(e, v) => onDeleteSubmit(v.result)"
        />
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { InteragencyApi } from '@openapi/registry-service';
import { notifyError, notifySuccess } from '@/utils/notify';
import ConfirmationForm from '@/components/forms/ConfirmationForm.vue';
import cloneDeep from 'lodash/cloneDeep';
import { unlink } from '@/services/registry-service';

const interagencyApi = new InteragencyApi();

@Component({
  components: {
    ConfirmationForm,
  },
})
export default class Header extends Vue {
  @Prop() isChanged: boolean;
  @Prop() isRequestChanged: boolean;
  @Prop() goBackFunc: Function;
  @Prop() editMode: boolean;
  @Prop() model: any;

  isDeleteModalVisible = false;
  loading = false;

  get isChildPage() {
    return !!this.$route.params.parentId;
  }

  get parentInteragency() {
    return this.$store.getters[
      'registryService/interagencies/getParentInteragency'
    ];
  }

  removeExcessData() {
    const newModel = cloneDeep(this.model);
    newModel.formRequest = newModel.formRequest?.id
      ? newModel.formRequest.id
      : newModel.formRequest;
    newModel.formResponse = newModel.formResponse?.id
      ? newModel.formResponse.id
      : newModel.formResponse;
    newModel.bpmnTemplate = newModel.bpmnTemplate?.id ? newModel.bpmnTemplate.id : '';
    newModel.attachments = newModel.attachments?.map((attch: any) => attch.id);
    return newModel;
  }

  async deleteInteragency() {
     if (this.isChildPage) {
       const { data } = await unlink(
          this,
          'Interagency',
          this.parentInteragency,
          'childrenInteragency',
          this.$route.params.id
        );
        if (!data.success) {
          throw Error('Couldn\'t unlink interagency');
        }
    }
    try {
      const { data } = await interagencyApi.deleteInteragency([
        this.$route.params.id,
      ]);
      if (data.success) {
        this.clearStore();
        notifySuccess(this.$tc('interagencies.message.success.delete'));
        this.goBackFunc();
      }
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    }
  }

  async updateInteragencyWithMapping() {
    const model = this.removeExcessData();
    if (this.isRequestChanged) {
      const newMapping = model.mapping.out;

      model.mapping.out = '';
      const { data } = await interagencyApi.updateInteragency([model]);

      if (data.success) {
        model.mapping.out = newMapping;
        await this.updateInteragency(model);
      }
    } else {
      await this.updateInteragency(model);
    }
  }

  async updateInteragency(model: any) {
    const { data } = await interagencyApi.updateInteragency([model]);
    if (data.success) {
      notifySuccess(this.$tc('interagencies.message.success.update'));

      this.$emit('saved');
      if (this.editMode) {
        this.$emit('set-edit-mode', false);
      }
    }
  }

  async saveInteragency() {
    this.loading = true;
    try {
      await this.updateInteragencyWithMapping();
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    } finally {
      this.loading = false;
    }
  }

  onDeleteSubmit(result: boolean) {
    if (result) {
      this.deleteInteragency();
    } else {
      this.isDeleteModalVisible = false;
    }
  }

  clearStore() {
    if (this.isChildPage) {
      this.$store.commit(
        'registryService/interagencies/setChildInteragency',
        null
      );
    } else {
      this.$store.commit(
        'registryService/interagencies/setParentInteragency',
        null
      );
    }
  }
}
</script>

<style scoped></style>
