<template>
  <div>
    <div class="container">
      <pie :chart-data="chartdata" :options="options" v-if="spendings[0] !== 0"></pie>
    </div>
    <div class="text-center">
      <b-button-group size="sm">
        <b-button v-for="tag in selected_tags"
                  :style="{'background-color': backgroundColor(tag)}">
          {{ tag }}
        </b-button>
      </b-button-group>
    </div>
  </div>
</template>

<script>
import pie from './charjs_donut'
import { mapGetters } from 'vuex'
import { total } from '../libs/data_processing'

export default {
  name: 'postesComparison',
  components: {
    'pie': pie
  },
  data () {
    return {
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
          display: false,
          position: 'left'
        }
      }
    }
  },
  computed: {
    ...mapGetters('datas', [
      'tag_filter_rows'
    ]),
    ...mapGetters('config', [
      'tag',
      'tags'
    ]),
    selected_tags () {
      var sel = Object.keys(this.tags)
      sel.push('sans tags')
      return sel
    },
    chartdata () {
      return {
        labels: this.selected_tags,
        datasets: [
          {
            label: 'Dépenses',
            data: this.spendings,
            backgroundColor: this.selected_tags.map(t => {
              return this.backgroundColor(t)
            })
          }
        ]
      }
    },
    spendings () {
      var tagsSpendings = this.selected_tags.map(tag => {
        if (tag) {
          return total(this.tag_filter_rows([tag]))
        } else {
          return 0
        }
      })
      tagsSpendings[tagsSpendings.length - 1] = total(this.tag_filter_rows([])) - tagsSpendings.reduce((sum, a) => sum + a, 0)
      return tagsSpendings
    }
  },
  methods: {
    backgroundColor (t) {
      if (this.tag(t)) {
        return this.tag(t).color
      } else {
        return '#A9A9A9'
      }
    }
  }
}

</script>

<style scope>
.container {
  position: relative;
  height: 420px;
}
</style>
