import axios from 'axios'

export default {
  namespaced: true,
  state: {
    role: {},
    roles: [],
    prem: {}
  },
  mutations: {
    setRoles(state, roles) {
      state.roles = roles;
    },
    setRole(state, role) {
      state.role = role;
    },
    setPrem(state, prem) {
      state.prem = prem
    },
    removeRole(state, role) {
      state.roles.pop(role);
    },
    addRole(state, role) {
      state.role = role;
      state.roles.push(role);
    },
    updateRole(state, role) {
      state.role = role;
      const item = state.roles.find(r => r.id === role.id);
      Object.assign(item, role);
      //https://stackoverflow.com/questions/51149729/updating-state-of-vuex-array-when-one-item-has-some-changes/51153076
    }
  },
  getters: {},
  actions: {
    getRoles({
      commit
    }, restaurantId) {
      axios
        .get(`/api/RestaurantRoles/GetRoles/${restaurantId}`)
        .then(result => commit("setRoles", result.data));
    },
    getRole({
      commit
    }, id) {
      axios
        .get(`/api/RestaurantRoles/${id}`)
        .then(result => commit("setRole", result.data));
    },
    getPremission({
      commit
    }, id) {
      axios
        .get(`/api/RestaurantRoles/GetPremission/${id}`)
        .then(result => commit("setPrem", result.data));
    },
    saveRole({
      commit
    }, role) {
      axios
        .post('/api/RestaurantRoles', role)
        .then(result => commit("addRole", result.data));
    },
    updateRole({
      commit
    }, role) {
      axios
        .put('/api/RestaurantRoles', role)
        .then(result => commit("updateRole", result.data));
    },
    removeRole({
      commit
    }, role) {
      axios
        .delete(`/api/RestaurantRoles/${role.id}`)
        .then(result => commit("removeRole", role));
    }
  }
}
