import "es6-promise/auto";
import { createStore } from "vuex";

import prepareLocations from "ChillActivityAssets/vuejs/Activity/store.locations";
import { whoami } from "ChillMainAssets/lib/api/user";
import { postLocation } from "ChillActivityAssets/vuejs/Activity/api";

const debug = process.env.NODE_ENV !== "production";

const store = createStore({
  strict: debug,
  state: {
    activity: window.entity, // activity is the event entity in this case (re-using component from activity bundle)
    currentEvent: null,
    availableLocations: [],
    me: null,
  },
  getters: {},
  actions: {
    addAvailableLocationGroup({ commit }, payload) {
      commit("addAvailableLocationGroup", payload);
    },
    updateLocation({ commit }, value) {
      // console.log("### action: updateLocation", value);
      let hiddenLocation = document.getElementById(
        "chill_activitybundle_activity_location",
      );
      if (value.onthefly) {
        const body = {
          type: "location",
          name:
            value.name === "__AccompanyingCourseLocation__" ? null : value.name,
          locationType: {
            id: value.locationType.id,
            type: "location-type",
          },
        };
        if (value.address.id) {
          Object.assign(body, {
            address: {
              id: value.address.id,
            },
          });
        }
        postLocation(body)
          .then((location) => (hiddenLocation.value = location.id))
          .catch((err) => {
            console.log(err.message);
          });
      } else {
        hiddenLocation.value = value.id;
      }
      commit("updateLocation", value);
    },
  },
  mutations: {
    setWhoAmiI(state, me) {
      state.me = me;
    },
    addAvailableLocationGroup(state, group) {
      state.availableLocations.push(group);
    },
    updateLocation(state, value) {
      // console.log("### mutation: updateLocation", value);
      state.activity.location = value;
    },
  },
});

whoami().then((me) => {
  store.commit("setWhoAmiI", me);
});

prepareLocations(store);

export default store;
