export default {
  name: 'permalink',
  
  getReducer: () => {
    const initialData = {
      params: "",
    };

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

  doConstructPermalinkParams: () => ({dispatch, store}) => {
    try {
      const visibleLayers = store.selectVisibleLayers();
      const extent = store.selectMapExtent();
      const basemapIdx = store.selectActiveBasemapIdx();
      const allBasemaps = store.selectBasemapList();
      const basemap = allBasemaps[basemapIdx].id;
      const paramPairs = [];
      
      if(visibleLayers.length) paramPairs.push(`layers=${visibleLayers.map(x => x.id).join(',')}`);
      
      paramPairs.push(`extent=${extent.map(x => Math.round(x * 100000)/100000).join()}`);
      paramPairs.push(`basemap=${basemap}`);
  
      const paramsString = `${paramPairs.join('&')}`;
      dispatch({ type: "PERMALINK_PARAMS_GENERATED",
        payload: {params: paramsString } });
    }
    catch(err) {
      const error = `${err.message}` || "Error creating permalink";
      dispatch({
        type:'PERMALINK_ERROR', 
        payload: { 
          err: error,
          notification: {
            level: "warning",
            title: "Permalink Error",
            message: `${JSON.stringify(error)}`,
          },
        },
      });
    }
   },

  selectPermalinkParams: (state) => {
    return state.permalink.params;
  },
}

