import XYZ from "ol/source/XYZ";
import TileLayer from "ol/layer/Tile";

export default {
  name: "radar",
  getReducer: () => {
    const initialData = { _shouldInit: false };
    return (state = initialData, { type, payload }) => {
      switch (type) {
        case "RADAR_INIT_STARTED":
          return Object.assign({}, state, payload);
        case "MAP_INITIALIZED":
          return Object.assign({}, state, {
            _shouldInit: true,
          });
        default:
          return state;
      }
    };
  },
  doRadarInit: () => ({ dispatch, store }) => {
    dispatch({
      type: "RADAR_INIT_STARTED",
      payload: {
        _shouldInit: false,
      },
    });
    const layer = new TileLayer({
      source: new XYZ({
        url:
          "https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/ridge::USCOMP-N0Q-0/{z}/{x}/{y}.png",
      }),
    });
    store.doLayersAdd({
      id: "current-radar",
      displayName: "Radar Data",
      collapsed: false,
    });
    store.doLayersAdd({
      parentId: "current-radar",
      displayName: "Current Radar",
      mapLayer: layer,
    });
  },
  reactRadarShouldInit: (state) => {
    if (state.radar._shouldInit) return { actionCreator: "doRadarInit" };
  },
};
