<template>
  <q-card>
    <q-card-actions align="right">
      <q-btn
        :color="color()"
        icon="mdi-trash-can"
        aria-label="Löschen"
        :disable="disabled()"
        @click="reverse(transaction)"
      />
    </q-card-actions>
    <q-card-section>
      <span>{{ timeStr }}: {{ transaction.amount }}</span>
    </q-card-section>
  </q-card>
</template>

<script lang="ts">
// TODO: Better styling

import { ref, computed, defineComponent, onUnmounted } 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'],
  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;

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

    function canReverse(transaction: FG.Transaction) {
      return (
        hasPermission('balance_reversal', store) ||
        (transaction.sender_id === store.state.user.currentUser?.userid &&
          Date.now() - transaction.time.getTime() < 10000)
      );
    }

    function color() {
      return canReverse(props.transaction) ? 'negative' : 'grey';
    }

    function disabled() {
      return !canReverse(props.transaction);
    }

    function reverse(transaction: FG.Transaction) {
      if (canReverse(transaction))
        store
          .dispatch('balance/revert', transaction)
          .then(() => {
            emit('reversed', transaction.id);
          })
          .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, disabled, color, reverse };
  }
});
</script>
