import { mapUtil } from "@/assets/js/map-util.js";


const map = {
  namespaced: true,
  state: {
    basemaps: [
      /*  {
         "id": 1,
         "title": "Fond mock",
         "layers": [
           {
             "id": 1,
             "title": "Open street map mock",
             "opacity": "1.50",
             "order": 2,
             "queryable": true
           }
         ]
       }, */
      /*       {
              "id": 10,
              "title": "Fond mock",
              "layers": [
                {
                  "id": 1,
                  "title": "Open street map mock",
                  "opacity": "1.50",
                  "order": 2,
                  "queryable": true
                }
              ]
            },
            {
              "id": 5,
              "title": "Fond mock",
              "layers": [
                {
                  "id": 1,
                  "title": "Open street map mock",
                  "opacity": "1.50",
                  "order": 2,
                  "queryable": true
                }
              ]
            }, */
    ],
    features: [],
    layers: [
      {
        "id": 1,
        "options": {
          "maxZoom": 20,
          "attribution": "© les contributeurs d’OpenStreetMap"
        },
        "title": "Open street map",
        "service": "https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png",
        "schema_type": "tms"
      }
    ],
    serviceMap: "https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png",
    optionsMap: {
      "attribution": "&copy; contributeurs d'<a href=\"https://osm.org/copyright\">OpenStreetMap</a>",
      "maxZoom": 20
    },
    //availableLayers: ["https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png"]
  },
  mutations: {
    SET_BASEMAPS(state, basemaps) {
      state.basemaps = basemaps;
    },
    CREATE_BASEMAP(state, id) {
      state.basemaps = [...state.basemaps, { id, layers: [] }]
    },
    DELETE_BASEMAP(state, id) {
      state.basemaps = state.basemaps.filter(el => el.id !== id)
    },
    UPDATE_BASEMAPS(state, basemaps) {
      state.basemaps = basemaps;
    },
    UPDATE_BASEMAP(state, { title, id, layers }) {
      const index = state.basemaps.findIndex((el) => el.id === id);
      if (index !== -1) {
        if (title) {
          state.basemaps[index].title = title
        }
        if (layers) {
          state.basemaps[index].layers = layers
        }
      }
    },
    DELETE_BASEMAP_LAYER(state, { basemapId, layerId }) {
      const index = state.basemaps.findIndex((el) => el.id === basemapId);
      if (index !== -1) {
        state.basemaps[index].layers = state.basemaps[index].layers.filter((el) => el.dataKey !== layerId)
      }
    },
    UPDATE_BASEMAP_LAYER(state, { basemapId, layerId, layer }) {
      const index = state.basemaps.findIndex((el) => el.id === basemapId);
      if (index !== -1) {
        state.basemaps[index].layers = state.basemaps[index].layers.map(
          (el) => el.dataKey === layerId ? layer : el
        )
      }
    },
  },

  getters: {
    basemapMaxId: (state) => state.basemaps.reduce((acc, curr) => {
      if (curr.id > acc) {
        return curr.id;
      } else {
        return acc;
      }
    }, 0)
  },

  actions: {
    INITIATE_MAP({ state, rootGetters }) {
      const project = rootGetters.project
      let mapDefaultViewCenter = [37.7749, -122.4194]; // defaultMapView.center;
      let mapDefaultViewZoom = 13; // defaultMapView.zoom;
      mapUtil.createMap({
        mapDefaultViewCenter,
        mapDefaultViewZoom,
      });

      // Load the layers.
      // - if one basemap exists, check in the localstorage if one active basemap is set
      // - if no current active basemap, get the first index
      // - if not, load the default map and service options

      // todo : create endpoints to get : 'baseMaps' ,'project' ,'layers' ,'serviceMap' ,'optionsMap' ,'features'
      let layersToLoad = null;
      if (state.baseMaps && state.baseMaps.length > 0) {
        // Use active one if exists, otherwise index 0 (first basemap in the list)
        const mapOptions =
          JSON.parse(localStorage.getItem("geocontrib-map-options")) || {};
        const basemapIndex =
          mapOptions &&
            mapOptions[project] &&
            mapOptions[project]["current-basemap-index"]
            ? mapOptions[project]["current-basemap-index"]
            : 0;
        layersToLoad = state.baseMaps[basemapIndex].layers;
        layersToLoad.forEach((layerToLoad) => {
          state.layers.forEach((layer) => {
            if (layer.id === layerToLoad.id) {
              layerToLoad = Object.assign(layerToLoad, layer);
            }
          });
        });
        layersToLoad.reverse();
      }
      mapUtil.addLayers(layersToLoad, state.serviceMap, state.optionsMap);

      // Remove multiple interactions with the map
      mapUtil.getMap().dragging.disable();
      mapUtil.getMap().doubleClickZoom.disable();
      mapUtil.getMap().scrollWheelZoom.disable();

      // Add the features
      const featureGroup = mapUtil.addFeatures(state.features);
      if (featureGroup && featureGroup.getLayers().length > 0) {
        mapUtil.getMap().fitBounds(featureGroup.getBounds());
      }

    },
    SAVE_BASEMAPS({ state }) {
      const data = JSON.stringify(state.basemaps);
      console.log("SAVE_BASEMAPS", data);
      // todo : call axios POST
    }
  }
}
export default map