<template>
  <div class="transaction-split field">
    <div class="columns is-mobile">
      <div class="column">
        <input
          v-model="checked"
          class="is-checkradio"
          :id="`user-${split.alias}`"
          type="checkbox"
          :name="`user-${split.alias}`"
        />
        <label
          :for="`user-${split.alias}`"
        >{{ split.alias }}, {{ $tc('transaction.split', split.weight, { count: split.weight }) }}</label>
      </div>
      <div class="column is-one-third">
        <div class="field has-addons">
          <div class="control">
            <a @click="plus" class="button is-primary">
              <awe-icon icon="plus" />
            </a>
          </div>
          <div class="control">
            <a @click="minus" class="button is-warning">
              <awe-icon icon="minus" />
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import IUser from '@/models/IUser'
import ISplit from '@/models/ISplit'

@Component
export default class TransactionSplit extends Vue {
  @Getter
  public user!: IUser | null
  @Prop({ type: Object, required: true })
  public split!: ISplit
  public checked: boolean = false

  public plus(): void {
    this.split.weight++
  }

  public minus(): void {
    this.split.weight = Math.max(this.split.weight - 1, 0)
  }

  @Watch('checked')
  public onCheckedChange(check: boolean): void {
    if (check && this.split.weight === 0) {
      this.split.weight = 1
    } else if (!check && this.split.weight > 0) {
      this.split.weight = 0
    }
  }

  @Watch('split.weight', { immediate: true })
  public onWeightChange(weight: number): void {
    if (weight === 0 && this.checked) {
      this.checked = false
    } else if (weight > 0 && !this.checked) {
      this.checked = true
    }
  }
}
</script>

<style scoped>
.input {
  float: left;
  max-width: 160px;
}
</style>
