import Vuex from 'vuex';
import Vue from 'vue';

Vue.config.devtools = true;
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    schedules: [],
  },

  actions: {
    getScheduleForm({ commit }, dataForm) {
      commit('setNewSchedules', dataForm);
    },
    getScheduleEditForm({ commit }, dataForm) {
      commit('setEditedSchedules', dataForm);
    },
    getSchedules({ commit }, schedulesFromBD) {
      commit('setInitialSchedules', schedulesFromBD);
    },
    getIdToDeleteSchedule({ commit }, deletedID) {
      commit('setDeleteSchedules', deletedID);
    },
  },

  mutations: {
    setNewSchedules(state, schedule) {
      state.schedules.push(schedule);
    },
    setEditedSchedules(state, editedSchedule) {
      const index = state.schedules.findIndex(schedule => schedule.schedule_id === editedSchedule.schedule_id);
      if (index !== -1) {
        Object.assign(state.schedules[index], editedSchedule);
      }
    },
    setInitialSchedules(state, schedulesFromBD) {
      if (!schedulesFromBD) {
        schedulesFromBD = [];
      }
      state.schedules = schedulesFromBD;
    },
    setDeleteSchedules(state, deletedID) {
      state.schedules = state.schedules.filter(schedule => schedule.schedule_id !== deletedID);
    },
  },
});
