import { fromLonLat } from "ol/proj";

export default {
  name: "rasterIdent",

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

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

  doRasterIdentRegister: () => ({ dispatch, store }) => {
    dispatch({
      type: "RASTER_IDENT_REGISTERED",
      payload: { shouldRegister: false },
    });
    store.doIdentifyAddCollection({
      onIdentify: store.doRasterIdentFire,
    });
  },

  doRasterIdentFire: (callback) => ({ store }) => {
    const map = store.selectMap();
    const visibleLayers = store.selectVisibleLayers();
    const coords = store.selectIdentifyCoordinates();
    const out = [];
    const c = fromLonLat(coords);
    const pixel = map.getPixelFromCoordinate(c);

    map.forEachLayerAtPixel(pixel, (layer, px) => {
      if (px) {
        const legendKey = `${px[0]}.${px[1]}.${px[2]}`;
        visibleLayers.forEach((visibleLayer) => {
          if (visibleLayer.mapLayer === layer && visibleLayer.legend) {
            let val = legendKey;
            if (
              visibleLayer.legend &&
              visibleLayer.legend.hasOwnProperty(legendKey)
            ) {
              val = visibleLayer.legend[legendKey];
            } else if (
              visibleLayer.legend &&
              visibleLayer.legend.hasOwnProperty("*")
            ) {
              val = visibleLayer.legend["*"];
            }
            out.push({
              dataset: visibleLayer.uid,
              layerName: visibleLayer.displayName,
              err: null,
              result: {
                [visibleLayer.uid]: {
                  type: "FeatureCollection",
                  features: [
                    {
                      type: "Feature",
                      geometry: {
                        type: "Point",
                        coordinates: coords,
                      },
                      properties: {
                        Class: val,
                      },
                    },
                  ],
                },
              },
            });
          }
        });
      }
    });
    return callback(null, out);
  },

  reactRasterIdentShouldRegister: (state) => {
    if (state.rasterIdent.shouldRegister)
      return { actionCreator: "doRasterIdentRegister" };
  },
};
