import v4 from "uuid/v4";
import { createSelector } from "redux-bundler";

export default {
  name: "southRegion",

  getReducer: () => {
    const initialData = {
      children: {},
      _shouldTryToCloseRegion: false,
    };

    return (state = initialData, { type, payload }) => {
      switch (type) {
        case "SOUTH_REGION_OPENED":
        case "SOUTH_REGION_CLOSED":
        case "SOUTH_REGION_TAB_CLOSED":
        case "SOUTH_REGION_TRY_CLOSE":
          return Object.assign({}, state, payload);
        default:
          return state;
      }
    };
  },

  doSouthRegionOpen: (options) => ({ dispatch, store }) => {
    const children = store.selectSouthRegionChildrenObj();
    const uid = v4();
    options.uid = uid;
    dispatch({
      type: "SOUTH_REGION_OPENED",
      payload: {
        children: { ...children, [uid]: options },
      },
    });
  },
  doSouthRegionClose: () => ({ dispatch, store }) => {
    dispatch({
      type: "SOUTH_REGION_CLOSED",
      payload: {
        children: {},
      },
    });
  },

  doSouthRegionCloseTab: (uid) => ({ dispatch, store }) => {
    const children = store.selectSouthRegionChildrenObj();
    delete children[uid];
    dispatch({
      type: "SOUTH_REGION_TAB_CLOSED",
      payload: {
        children: { ...children },
        _shouldTryToCloseRegion: true,
      },
    });
  },

  doSouthRegionTryClose: () => ({ dispatch, store }) => {
    dispatch({
      type: "SOUTH_REGION_TRY_CLOSE",
      payload: { _shouldTryToCloseRegion: false },
    });
    const children = store.selectSouthRegionChildren();
    if (!children.length) store.doSouthRegionClose();
  },

  selectSouthRegionChildrenObj: (state) => {
    return state.southRegion.children;
  },
  
  selectSouthRegionChildren: createSelector(
    "selectSouthRegionChildrenObj",
    (children) => {
      const out = [];
      for (var key in children) {
        out.push(children[key]);
        out.unshift(out.pop());
      }
      return out;
    }
  ),

  reactSouthRegionTryToCloseRegion: (state) => {
    if (state.southRegion._shouldTryToCloseRegion)
      return { actionCreator: "doSouthRegionTryClose" };
  },

};
