<template>
  <q-card>
    <BalanceHeader
      @update:user="senderUpdated"
      :showSelector="showSelector"
      @open-history="openHistory"
    />
    <q-separator />
    <q-card-section class="row q-col-gutter-md items-center">
      <div class="col-sm-4 col-xs-12">
        <q-input v-model.number="amount" type="number" filled label="Betrag" step="0.1" min="0" />
      </div>
      <div class="col-sm-4 col-xs-6">
        <UserSelector :user="receiver" @update:user="receiverUpdated" label="Empfänger" />
      </div>
      <div class="col-sm-4 col-xs-6">
        <q-btn
          style="width: 100%"
          color="primary"
          :disable="sendDisabled"
          label="Senden"
          @click="sendAmount"
        />
      </div>
    </q-card-section>
  </q-card>
</template>

<script lang="ts">
import { computed, ref, defineComponent } from '@vue/composition-api';
import { hasPermission } from 'src/utils/permission';
import { StateInterfaceBalance } from '../store/balance';
import { Store } from 'vuex';
import UserSelector from 'src/plugins/user/components/UserSelector.vue';
import BalanceHeader from '../components/BalanceHeader.vue';
import PERMISSIONS from '../permissions';

export default defineComponent({
  name: 'BalanceTransfer',
  components: { BalanceHeader, UserSelector },
  setup(_, { root, emit }) {
    const store: Store<StateInterfaceBalance> = <Store<StateInterfaceBalance>>root.$store;

    const showSelector = computed(() => hasPermission(PERMISSIONS.SEND_OTHER, store));
    const sender = ref(store.state.user.currentUser);
    const receiver = ref<FG.User | undefined>(undefined);
    const amount = ref<number>(0);

    const sendDisabled = computed(() => {
      return !(
        receiver.value &&
        sender.value &&
        sender.value.userid != receiver.value.userid &&
        amount.value > 0
      );
    });

    function senderUpdated(selectedUser: FG.User) {
      console.log(selectedUser);
      sender.value = selectedUser;
    }
    function receiverUpdated(selectedUser: FG.User) {
      receiver.value = selectedUser;
    }

    function sendAmount() {
      store
        .dispatch('balance/changeBalance', {
          amount: amount.value,
          sender: sender.value?.userid,
          user: receiver.value?.userid,
        })
        .catch((err) => console.log(err));
    }

    function openHistory() {
      emit('open-history');
    }

    return {
      sender,
      receiver,
      amount,
      sendAmount,
      showSelector,
      senderUpdated,
      receiverUpdated,
      sendDisabled,
      openHistory,
    };
  },
});
</script>
