import buffer from "@turf/buffer";
import { point } from "@turf/helpers";
import { polygon } from "@turf/helpers";
import disjoint from "@turf/boolean-disjoint";
import bbox from "@turf/bbox";
import GeoJSON from "ol/format/GeoJSON";
import { transformExtent } from "ol/proj";

const geoJSON = new GeoJSON();

export default {
  name: "vectorIdent",

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

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

  doVectorIdentRegister:
    () =>
    ({ dispatch, store }) => {
      dispatch({
        type: "VECTOR_IDENT_REGISTERED",
        payload: { shouldRegister: false },
      });
      store.doIdentifyAddCollection({
        onIdentify: store.doVectorIdentFire,
      });
    },

  doVectorIdentFire:
    (callback) =>
    ({ store }) => {
      const layers = store.selectVisibleLayers();
      const identifyFeature = store.doSetIdentifyFeature();
      const out = [];

      const identifyExtent = transformExtent(
        bbox(identifyFeature),
        "EPSG:4326",
        "EPSG:3857"
      );

      layers.forEach((lyr) => {
        if (lyr.identifyType && lyr.identifyType === "arcgisvector") {
          const { mapLayer } = lyr;
          const outFeatures = [];
          const src = mapLayer.getSource();
          src.forEachFeatureIntersectingExtent(identifyExtent, (f) => {
            const geoJsonFeature = geoJSON.writeFeatureObject(f, {
              featureProjection: "EPSG:3857",
              dataProjection: "EPSG:4326",
            });
            if (!disjoint(identifyFeature, geoJsonFeature))
              outFeatures.push(geoJsonFeature);
          });
          out.push({
            dataset: lyr.uid,
            layerName: lyr.displayName,
            err: null,
            result: {
              [lyr.uid]: {
                type: "FeatureCollection",
                features: outFeatures,
              },
            },
          });
        }
      });
      return callback(null, out);
    },

  reactVectorIdentShouldRegister: (state) => {
    if (state.vectorIdent.shouldRegister)
      return { actionCreator: "doVectorIdentRegister" };
  },
};
