<template>
  <div class="box">
    <button @click="fetchSolution" class="button is-primary">FetchSolution</button>
    <hr />
    <div v-if="template">
      <div class="columns">
        <div v-for="day_meals in itemsGroupedByDay"
             class="column">
          <strong> {{ day_meals[0] }}</strong>
          <p v-for="meal in day_meals[1]">
            <span class="tag is-light">{{ meal.value.title }}</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

const groupBy = function(items, keyGetter) {
  const map = new Map();
  items.forEach((item) => {
    const key = keyGetter(item);
    const collection = map.get(key);
    if (!collection) {
      map.set(key, [item]);
    } else {
      collection.push(item);
    }
  });
  return map;
};

const DAYS = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"];
const compareWeekDay = function(entryA, entryB) {
  return DAYS.indexOf(entryA[0]) - DAYS.indexOf(entryB[0]);
}

const MEALS = ["Breakfast", "Lunch", "Dinner"];
const compareMealType = function(mealA, mealB) {
  return MEALS.indexOf(mealA.key[1]) - MEALS.indexOf(mealB.key[1]);
}

export default {
  name: 'Planner',
  data () {
    return {
    template: null,
  };},
  methods: {
    fetchSolution: function() {
      fetch("http://localhost:8000/api/solver/one")
        .then((res) => res.json())
        .then((data) => this.template = data)
        .catch((err) => console.log(err));
    }
  },
  computed: {
    itemsGroupedByDay: function() {
      let grouped = groupBy(this.template.items, item => item.key[0]);
      let sorted = new Map([...grouped.entries()].sort(compareWeekDay));
      sorted.forEach((meals) => meals.sort(compareMealType));
      return sorted;
    }
  }
}
</script>
