import { State } from "./../index";
import { ActionContext } from "vuex";

export interface FullCalendarState {
  currentView: {
    start: Date | null;
    end: Date | null;
  };
  key: number;
}

type Context = ActionContext<FullCalendarState, State>;

export default {
  namespaced: true,
  state: (): FullCalendarState => ({
    currentView: {
      start: null,
      end: null,
    },
    key: 0,
  }),
  mutations: {
    setCurrentDatesView: function (
      state: FullCalendarState,
      payload: { start: Date; end: Date },
    ): void {
      state.currentView.start = payload.start;
      state.currentView.end = payload.end;
    },
    increaseKey: function (state: FullCalendarState): void {
      state.key = state.key + 1;
    },
  },
  actions: {
    setCurrentDatesView(
      ctx: Context,
      { start, end }: { start: Date | null; end: Date | null },
    ): Promise<null> {
      console.log("dispatch setCurrentDatesView", { start, end });

      if (
        ctx.state.currentView.start !== start ||
        ctx.state.currentView.end !== end
      ) {
        ctx.commit("setCurrentDatesView", { start, end });
      }

      if (start !== null && end !== null) {
        return Promise.all([
          ctx
            .dispatch(
              "calendarRanges/fetchRanges",
              { start, end },
              { root: true },
            )
            .then((_) => Promise.resolve(null)),
          ctx
            .dispatch(
              "calendarRemotes/fetchRemotes",
              { start, end },
              { root: true },
            )
            .then((_) => Promise.resolve(null)),
          ctx
            .dispatch(
              "calendarLocals/fetchLocals",
              { start, end },
              { root: true },
            )
            .then((_) => Promise.resolve(null)),
        ]).then((_) => Promise.resolve(null));
      } else {
        return Promise.resolve(null);
      }
    },
  },
};
