<template>
  <q-card v-bind:class="{ 'bg-grey': isReversed }">
    <q-card-section class="row items-start justify-between">
      <div class="col text-center">
        <div
          v-bind:class="{ 'text-negative': isNegative() }"
          class="text-weight-bold"
          style="font-size: 2em"
        >
          <span v-if="isNegative()">-</span>{{ transaction.amount.toFixed(2) }}&#8239;€
        </div>
        <div>{{ text }}</div>
        <div>{{ timeStr }}</div>
      </div>
      <div class="col" style="text-align: right">
        <q-btn
          color="negative"
          aria-label="Reverse transaction"
          icon="mdi-trash-can"
          square
          :disable="!canReverse"
          @click="reverse"
        />
      </div>
    </q-card-section>
  </q-card>
</template>

<script lang="ts">
import { ref, computed, defineComponent, onUnmounted, onMounted } from '@vue/composition-api';
import { hasPermission } from 'src/utils/permission';
import { formatDateTime } from 'src/utils/datetime';
import { StateInterfaceBalance } from 'src/plugins/balance/store/balance';
import { Store } from 'vuex';

interface Props {
  transaction: FG.Transaction;
}

export default defineComponent({
  name: 'Transaction',
  props: {
    transaction: {
      type: Object,
      required: true
    }
  },
  watch: { transaction: 'refreshText' },
  setup(props: Props, { root, emit }) {
    const now = ref(Date.now());
    const ival = setInterval(() => (now.value = Date.now()), 1000);
    const store: Store<StateInterfaceBalance> = <Store<StateInterfaceBalance>>root.$store;
    const text = ref('');

    onUnmounted(() => clearInterval(ival));
    onMounted(() => refreshText());

    const isNegative = () => props.transaction.sender_id === store.state.user.currentUser?.userid;

    const refreshText = async () => {
      if (isNegative()) {
        text.value = 'Anschreiben';
        if (props.transaction.receiver_id !== null) {
          const user = <FG.User>await store.dispatch('user/getUser', {
            userid: props.transaction.receiver_id
          });
          text.value = `Gesendet an ${user.display_name}`;
        }
      } else {
        text.value = 'Gutschrift';
        if (props.transaction.sender_id !== null) {
          const user = <FG.User>await store.dispatch('user/getUser', {
            userid: props.transaction.sender_id
          });
          text.value = `Bekommen von ${user.display_name}`;
        }
      }
    };

    const isReversed = computed(
      () => props.transaction.reversal_id != undefined || props.transaction.original_id != undefined
    );

    const canReverse = computed(
      () =>
        !isReversed.value &&
        (hasPermission('balance_reversal', store) ||
          (props.transaction.sender_id === store.state.user.currentUser?.userid &&
            now.value - props.transaction.time.getTime() < 10000))
    );

    function reverse() {
      if (canReverse.value)
        store
          .dispatch('balance/revert', props.transaction)
          .then(() => {
            emit('update:transaction', props.transaction);
          })
          .catch(error => console.log(error));
    }

    const timeStr = computed(() => {
      const elapsed = (now.value - props.transaction.time.getTime()) / 1000;
      if (elapsed < 60) return `Vor ${elapsed.toFixed()} s`;
      return formatDateTime(props.transaction.time, elapsed > 12 * 60 * 60, true, true) + ' Uhr';
    });

    return { timeStr, reverse, isNegative, text, refreshText, canReverse, isReversed };
  }
});
</script>