import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import { A } from '@ember/array';
import { inject as service } from '@ember/service';

export default class MealListComponent extends Component {
  @service store;
  @tracked items = A([]);

  constructor() {
    super(...arguments);
    this.assignExistingItems();
  }

  get sortedItems() {
    return this.items.sortBy('listOrder');
  }

  async assignExistingItems() {
    let items = await this.store.peekAll('meal');
    this.items = items;
  }

  @action
  async reorderMeals(reorderedMeals) {
    let orderedIds = reorderedMeals.map(meal => meal.id);

    for (let index = 0; index < orderedIds.length; index++) {
      let meal = await this.store.peekRecord('meal', orderedIds[index]);
      meal.listOrder = index;
    }
  }
}
