// Possibly deprecated
function formatUrl(options) {
  let url = `${options.root}/cop-api/identify?`;
  const params = [];
  for (var key in options) {
    if (key !== "root") params.push(key + "=" + options[key].toString());
  }
  url += params.join("&");
  return url;
}

export default {
  name: "cmIdent",

  getReducer() {
    const initialData = {
      shouldRegister: true,
    };

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

  doCmIdentRegister:
    () =>
    ({ dispatch, store }) => {
      dispatch({
        type: "CM_IDENT_REGISTERED",
        payload: { shouldRegister: false },
      });
      store.doIdentifyAddCollection({
        onIdentify: store.doCmIdentFire,
      });
    },

  doCmIdentFire:
    (callback) =>
    ({ dispatch, store, anonGet }) => {
      const coords = store.selectIdentifyCoordinates();
      const root = store.selectApiRoot();
      const visibleLayers = store.selectVisibleCmLayers();
      const resolution = store.selectResolution();

      if (!visibleLayers.length) return callback(null, []);

      const params = {
        root: root,
        tables: visibleLayers,
        mapExtent: store.selectMapExtent(),
        imageDisplay: store.selectMapImageDisplay(),
      };

      if (typeof coords[0] === "number") {
        params.lonlat = coords;
        params.dist = resolution * 5;
      } else {
        params.bbox = coords;
      }
      const url = formatUrl(params);

      anonGet(url, (err, response, body) => {
        if (err || response.statusCode !== 200) {
          callback({ err: err, response: response });
        } else {
          const data = JSON.parse(body);
          data.pop();
          callback(null, data);
        }
      });
    },

  reactCmIdentShouldRegister: (state) => {
    if (state.cmIdent.shouldRegister)
      return { actionCreator: "doCmIdentRegister" };
  },
};
