import "es6-promise/auto";
import { Store, createStore } from "vuex";
import { InjectionKey } from "vue";
import me, { MeState } from "./modules/me";
import fullCalendar, { FullCalendarState } from "./modules/fullcalendar";
import calendarRanges, { CalendarRangesState } from "./modules/calendarRanges";
import calendarRemotes, {
  CalendarRemotesState,
} from "./modules/calendarRemotes";
import { whoami } from "../../../../../../ChillMainBundle/Resources/public/lib/api/user";
import { User } from "../../../../../../ChillMainBundle/Resources/public/types";
import locations, { LocationState } from "./modules/location";
import calendarLocals, { CalendarLocalsState } from "./modules/calendarLocals";

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

export interface State {
  calendarRanges: CalendarRangesState;
  calendarRemotes: CalendarRemotesState;
  calendarLocals: CalendarLocalsState;
  fullCalendar: FullCalendarState;
  me: MeState;
  locations: LocationState;
}

export const key: InjectionKey<Store<State>> = Symbol();

const futureStore = function (): Promise<Store<State>> {
  return whoami().then((user: User) => {
    const store = createStore<State>({
      strict: debug,
      modules: {
        me,
        fullCalendar,
        calendarRanges,
        calendarRemotes,
        calendarLocals,
        locations,
      },
      mutations: {},
    });

    store.commit("me/setWhoAmi", user, { root: true });
    store.dispatch("locations/getLocations", null, { root: true }).then((_) => {
      return store.dispatch("locations/getCurrentLocation", null, {
        root: true,
      });
    });

    return Promise.resolve(store);
  });
};

export default futureStore;
