<template>
  <div class="import">
    <h1>Analyse</h1>
    <b-container fluid>
      <b-row class="date-selector">
        <b-col sm="1"><label for="start"> Entre </label> </b-col>
        <b-col sm="3"><b-form-input id="start" type="date" v-model="start"></b-form-input></b-col>
        <b-col sm="1"><label for="end"> et </label></b-col>
        <b-col sm="3"><b-form-input id="end" type="date" v-model="end"></b-form-input></b-col>
        <b-col sm="3"><label for="spending"> Uniquement les dépenses </label></b-col>
        <b-col sm="1"><b-form-checkbox id="spending" v-model="spending"></b-form-checkbox></b-col>
      </b-row>
    </b-container>

    <b-table striped hover :items="filter_rows" :fields='fields'></b-table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

var today = new Date()
var monthAgo = new Date()
monthAgo.setMonth(monthAgo.getMonth() - 1)

export default {
  name: 'home',
  components: {
  },
  data () {
    return {
      fields: [
        {
          key: 'Date',
          sortable: true,
          formatter: this.table_date_format
        },
        {
          key: 'Montant',
          sortable: true
        },
        {
          key: 'Libellé',
          sortable: true
        }
      ],
      spending: true,
      start: monthAgo.toISOString().split('T')[0],
      end: today.toISOString().split('T')[0]
    }
  },
  mounted: function () {
    this.$store.dispatch('datas/find_csv')
  },
  computed: {
    ...mapGetters({
      'csvs': 'datas/csvs',
      'rows': 'datas/rows'
    }),
    filter_rows () {
      return this.filter_date(this.filter_spending(this.rows))
    }
  },
  methods: {
    table_date_format (date) {
      return date
    },
    filter_spending (rows) {
      if (this.spending) {
        return rows.filter(x => x.Montant < 0)
      } else {
        return rows
      }
    },
    filter_date (rows) {
      var start = new Date(this.start)
      var end = new Date(this.end)
      return rows.filter(x => {
        return (new Date(x.Date) >= start) & (new Date(x.Date) < end)
      })
    }
  }
}
</script>

<style scoped>
.date-selector {
    padding: 1rem;
}

</style>
