let req = null;
export const treeViewDownload = {
  name: "treeviewDownload",

  getReducer() {
    const initialData = {
      enabled: false,
      _shouldFormatData: false,
      _shouldFormatUrl: false,
      activeFormat: "geojson",
      formats: ["geojson", "shapefile", "FileGDB"],
      data: null,
      url: null,
    };

    return (state = initialData, { type, payload }) => {
      switch (type) {
        case "TREEVIEW_DETAILS_DISPLAYED":
          return Object.assign({}, state, {
            _shouldFormatUrl: true,
          });
        case "TREEVIEW_DOWNLOAD_ENABLED":
        case "TREEVIEW_DOWNLOAD_FORMAT_UPDATED":
        case "TREEVIEW_DOWNLOAD_FETCHED_DATA":
        case "TREEVIEW_DOWNLOAD_FORMAT_INITIATED":
        case "TREEVIEW_DOWNLOAD_FORMAT_URL_INITIATED":
        case "TREEVIEW_DOWNLOAD_FORMAT_URL_COMPLETED":
          return Object.assign({}, state, payload);
        default:
          return state;
      }
    };
  },
  doEnableTreeViewLayerDownload:
    () =>
    ({ dispatch }) => {
      dispatch({
        type: "TREEVIEW_DOWNLOAD_ENABLED",
        payload: { enabled: true },
      });
    },
  doUpdateTreeViewLayerDownloadFormat:
    (e) =>
    ({ dispatch }) => {
      const layer = store.selectTreeViewSelectedItem();
      const format = e.target.value;
      let url = null;
      if (layer.identifyType === "MAP") {
        const params = `&service=WFS&version=1.1.0&request=GetFeature&typeName=${layer.layerList}&outputformat=${format}&outfile=${layer.layerList}`;
        url = `${layer.url}${params}`;
      }

      dispatch({
        type: "TREEVIEW_DOWNLOAD_FORMAT_UPDATED",
        payload: { activeFormat: format, url: url },
      });
    },
  doFetchLayerInfoForTreeView:
    (url) =>
    ({ dispatch, store, anonGet }) => {
      if (req) req.abort();
      req = anonGet(url, (err, response, body) => {
        if (err || response.statusCode !== 200) {
          console.log(err);
          dispatch({
            type: "TREEVIEW_DOWNLOAD_FETCHED_DATA",
            payload: {
              data: null,
              notification: {
                level: "danger",
                title: "Error Retrieving Data",
              },
            },
          });
        }
        try {
          const data = JSON.parse(body);
          dispatch({
            type: "TREEVIEW_DOWNLOAD_FETCHED_DATA",
            payload: { data: data, _shouldFormatData: true },
          });
        } catch (error) {
          console.log(error);
          dispatch({
            type: "TREEVIEW_DOWNLOAD_FETCHED_DATA",
            payload: {
              data: null,
              notification: {
                level: "danger",
                title: "Error Retrieving Data",
              },
            },
          });
        }
      });
    },
  doFormatTreeViewDownloadUrl:
    () =>
    ({ dispatch, store }) => {
      dispatch({
        type: "TREEVIEW_DOWNLOAD_FORMAT_URL_INITIATED",
        payload: { _shouldFormatUrl: false },
      });
      const layer = store.selectTreeViewSelectedItem();
      const format = store.selectTreeViewDownloadActiveFormat();
      let url = null;
      switch (layer.identifyType) {
        case "MAP":
          const params = `&service=WFS&version=1.1.0&request=GetFeature&typeName=${layer.layerList}&outputformat=${format}&outfile=${layer.layerList}`;
          url = `${layer.url}${params}`;
          break;
        default:
          break;
      }
      dispatch({
        type: "TREEVIEW_DOWNLOAD_FORMAT_URL_COMPLETED",
        payload: { url: url },
      });
    },
  doFormatTreeViewDownloadData:
    () =>
    ({ dispatch, store }) => {
      dispatch({
        type: "TREEVIEW_DOWNLOAD_FORMAT_INITIATED",
        payload: { _shouldFormatData: false },
      });
      const format = store.selectTreeViewDownloadActiveFormat();
      const data = store.selectTreeViewDownloadLayerData();
    },
  selectTreeViewDownloadEnabled: (state) => {
    return state.treeviewDownload.enabled;
  },
  selectTreeViewDownloadActiveFormat: (state) => {
    return state.treeviewDownload.activeFormat;
  },
  selectTreeViewDownloadFormats: (state) => {
    return state.treeviewDownload.formats;
  },
  selectTreeViewDownloadLayerData: (state) => {
    return state.treeviewDownload.data;
  },
  selectTreeViewDownloadLayerUrl: (state) => {
    return state.treeviewDownload.url;
  },
  reactTreeViewDownloadShouldFormatData: (state) => {
    if (state.treeviewDownload._shouldFormatData)
      return { actionCreator: "doFormatTreeViewDownloadData" };
  },
  reactTreeViewDownloadShouldFormatUrl: (state) => {
    if (state.treeviewDownload._shouldFormatUrl)
      return { actionCreator: "doFormatTreeViewDownloadUrl" };
  },
};
export default treeViewDownload;
