<template>
  <div class="row pin-top">
    <div class="col s12 m4 card darken-4 grey grey-text text-lighten-2">
      <table class="card-content">
        <tbody style="max-height:300px">
          <tr
            v-for="item in items"
            v-show="item.count > 0"
            :key="'bon_'+item.short"
          >
            <td class="right-align">
              {{ item.count }} &times;
            </td>
            <td>{{ item.name }}</td>
            <td class="right-align">
              <TweenedNumber
                :wert="item.sum"
                :einheit="'€'"
                :precision="2"
              />
            </td>
          </tr>
        </tbody>
        <tfoot>
          <tr class="white-text">
            <th class="right-align">
              <TweenedNumber
                :wert="totalCount"
              />
            </th>
            <th>
              Artikel
            </th>
            <th class="right-align">
              <TweenedNumber
                :wert="totalSum"
                :einheit="'€'"
                :precision="2"
              />
            </th>
          </tr>
        </tfoot>
      </table>
    </div>
    <div class="col s12 m8">
      <div class="row">
        <div
          v-for="a in items"
          :key="'bon_btn_'+a.short"
          class="col s3"
        >
          <button
            class="waves-effect waves-light btn-large btn-flat col s12"
            @click="a.count++;a.sum+=a.price;"
          >
            {{ a.short }}
          </button>
        </div>
      </div>
      <div class="row">
        <div class="col s3">
          <button
            class="waves-effect waves-light btn-large orange col s12"
            @click="resetBon"
          >
            Reset
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TweenedNumber from './TweenedNumber';

export default {
  name: "Calculator",
  components: { TweenedNumber },
  props: {
    articles: {
      type: Array,
      default() { return []; }
    }
  },
  data() {
    return {
      items: []
    }
  },
  computed: {
    totalSum() {
      return this.items.reduce((total, item) => {
        return total + item.sum;
      }, 0);
    },
    totalCount() {
      return this.items.reduce((total, item) => {
        return total + item.count;
      }, 0);
    }
  },
  mounted() {
    this.resetBon();
  },
  methods: {
    resetBon() {
      this.items = this.articles.map(a => {
        return {
          count: 0,
          name: a.name,
          short: a.short,
          price: a.portion.price,
          sum: 0,
        }
      });
    }
  }
}
</script>

<style>

</style>