import { Location } from "../../../../../../../ChillMainBundle/Resources/public/types";
import { State } from "../index";
import { Module } from "vuex";
import { getLocations } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/locations";
import { whereami } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/user";

export interface LocationState {
  locations: Location[];
  locationPicked: Location | null;
  currentLocation: Location | null;
}

export default {
  namespaced: true,
  state: (): LocationState => {
    return {
      locations: [],
      locationPicked: null,
      currentLocation: null,
    };
  },
  getters: {
    getLocationById:
      (state) =>
      (id: number): Location | undefined => {
        return state.locations.find((l) => l.id === id);
      },
  },
  mutations: {
    setLocations(state, locations): void {
      state.locations = locations;
    },
    setLocationPicked(state, location: Location | null): void {
      if (null === location) {
        state.locationPicked = null;
        return;
      }

      state.locationPicked =
        state.locations.find((l) => l.id === location.id) || null;
    },
    setCurrentLocation(state, location: Location | null): void {
      if (null === location) {
        state.currentLocation = null;
        return;
      }

      state.currentLocation =
        state.locations.find((l) => l.id === location.id) || null;
    },
  },
  actions: {
    getLocations(ctx): Promise<void> {
      return getLocations().then((locations) => {
        ctx.commit("setLocations", locations);
        return Promise.resolve();
      });
    },
    getCurrentLocation(ctx): Promise<void> {
      return whereami().then((location) => {
        ctx.commit("setCurrentLocation", location);
      });
    },
  },
} as Module<LocationState, State>;
