import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import UIStore, { UILayer } from "./state";

const initialState: UIStore = {
  layers: [],
};

export interface AddLayerPayload {
  id: string;
  data: UILayer;
}

export interface LayerActionPayload {
  id: string;
}

const uiSlice = createSlice({
  name: "ui",
  initialState,
  reducers: {
    addLayer(state, action: PayloadAction<AddLayerPayload>) {
      state.layers.push({ ...action.payload, visible: false });
    },
    removeLayer(state, action: PayloadAction<LayerActionPayload>) {
      const index = state.layers.findIndex(
        (layer) => layer.id == action.payload.id
      );
      if (index < 0) {
        return;
      }
      state.layers.splice(index, 1);
    },
    showLayer(state, action: PayloadAction<LayerActionPayload>) {
      const index = state.layers.findIndex(
        (layer) => layer.id == action.payload.id
      );
      if (index < 0) {
        return;
      }

      state.layers[index] = { ...state.layers[index], visible: true };
    },
    hideLayer(state, action: PayloadAction<LayerActionPayload>) {
      const index = state.layers.findIndex(
        (layer) => layer.id == action.payload.id
      );
      if (index < 0) {
        return;
      }
      state.layers[index] = { ...state.layers[index], visible: false };
    },
  },
});

export const { addLayer, removeLayer, showLayer, hideLayer } = uiSlice.actions;
export default uiSlice.reducer;
