<template>
  <div class="col-sm-4 col-xs-12">
    <q-input v-model.number="amount" type="number" filled label="Betrag" step="0.1" min="0" suffix="€" />
  </div>
  <div class="col-sm-4 col-xs-6">
    <UserSelector v-model="receiver" 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>
</template>
<script lang="ts">
import { computed, defineComponent, PropType, ref } from 'vue';
import UserSelector from '@flaschengeist/users/src/components/UserSelector.vue';
import { useBalanceStore } from '../store';
import { useUserStore } from '@flaschengeist/api';
export default defineComponent({
  name: 'BalanceTransferBody',
  components: { UserSelector },
  props: {
    user: {
      type: [Object, String] as PropType<FG.User | string>,
      required: true,
    },
  },
  emits: {
    changeBalance: ({ sender, receiver }: { sender: FG.User; receiver: FG.User }) => sender && receiver,
  },
  setup(props, { emit }) {
    const store = useBalanceStore();
    const userStore = useUserStore();
    const receiver = ref<FG.User | undefined>(undefined);
    const amount = ref<number>(0);
    const sender = computed(() =>
      (<FG.User>props.user).userid
        ? <FG.User>props.user
        : <FG.User>userStore.users.find((a) => a.userid === <string>props.user)
    );

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

    async function sendAmount() {
      if (receiver.value) {
        await store.changeBalance(amount.value, receiver.value, sender.value);
        emit('changeBalance', { sender: sender.value, receiver: receiver.value });
      }
    }
    return {
      receiver,
      sender,
      amount,
      sendAmount,
      sendDisabled,
    };
  },
});
</script>

<style scoped></style>
