<template>
<ul>
    <li>
    <h2>Période</h2>
    </li>
    <li>
      <input type="month" v-model="range.start">
      <input type="month" v-model="range.end">
    </li>
    <li>
        <button @click="setRange6months" :active='selected=="month"'>6 mois</button>
        <button @click="setRange1year" :active='selected=="year"'>1 an</button>
        <button @click="setRangeAll" :active='selected=="all"'>Tout</button>
    </li>
</ul>

</template>

<script>

import { mapGetters, mapActions } from 'vuex'
import { addMonths, format, parseISO } from 'date-fns'

const today = new Date();

export default {
    name: 'MonthSelector',
    components: {
    },
    data () {
        return {
            selected: "",
            }
    },
    computed: {
        ...mapGetters('travail', {
            range: "Range",
            monthsDate: "MonthsDate",
        })
    },
    methods: {
        ...mapActions('travail', {
            setRange: "setRange",
        }),
        setRange6months: function () {
            const start = addMonths(new Date(), -6)
            const range = {
                start: format(start, 'yyyy-MM'), 
                end: format(today, 'yyyy-MM'), 
            }
            this.selected = "month"
            this.setRange(range)
        }, 
        setRange1year: function () {
            const start = addMonths(new Date(), -12)
            const range = {
                start: format(start, 'yyyy-MM'), 
                end: format(today, 'yyyy-MM'), 
            }
            this.selected = "year"
            this.setRange(range)
        }, 
        setRangeAll: function () {
            const dates = this.monthsDate.map(a => parseISO(a, "yyyy-MM", new Date()))
            const start = dates.reduce((a, b) => (a.MeasureDate > b.MeasureDate ? a: b))
            const end = dates.reduce((a, b) => (a.MeasureDate > b.MeasureDate ? b: a))
            const range = {
                start: format(start, 'yyyy-MM'), 
                end: format(end, 'yyyy-MM'),
            }
            this.selected = "all"
            this.setRange(range)
        }, 
    },
}
</script>

<style scoped>
ul {
        list-style-type: none;
        padding: 0;
        display: flex;
        flex-flow: column wrap;
}
ul > * {
    margin-top: 10px;
}
li {
        list-style-type: none;
        display: flex;
        flex-flow: row;
        justify-content: space-around;

}
h2 {
    margin: 0;
}
input {
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    display: inline-block;
    font-size: 16px;
    border-radius: 5px;
    color: black;
}
button {
    flex-basis: 33%;
    height: 3rem;
    background-color: white;

}

</style>
