// Redux Slice: redux/slices/analogInputs/analogInputsSlice.ts
import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import type { AnalogInput } from "@/types/analogInput";

export interface AnalogInputsState {
  [key: string]: AnalogInput;
}

// Standardwerte für Eingänge
const defaultAnalogInput: AnalogInput = {
  id: 0,
  value: 0,
  label: "",
  name: "",
  uW: false,
  uG: false,
  oW: false,
  oG: false,
};

// Initialer Zustand
const initialState: AnalogInputsState = {
  win_analogInputs1: { ...defaultAnalogInput },
  win_analogInputs2: { ...defaultAnalogInput },
  win_analogInputs3: { ...defaultAnalogInput },
  win_analogInputs4: { ...defaultAnalogInput },
  win_analogInputs5: { ...defaultAnalogInput },
  win_analogInputs6: { ...defaultAnalogInput },
  win_analogInputs7: { ...defaultAnalogInput },
  win_analogInputs8: { ...defaultAnalogInput },
};

// Dynamisch Mock-Daten aus `window` abrufen
export const loadFromWindow = createAsyncThunk(
  "analogInputs/loadFromWindow",
  async (_, { dispatch }) => {
    const data: Partial<AnalogInputsState> = {};

    for (let i = 1; i <= 8; i++) {
      const key = `win_analogInputs${i}`;
      const value = (window as unknown as { [key: string]: unknown })[key];

      if (Array.isArray(value) && value.length === 7) {
        data[key] = {
          id: value[0],
          value: value[1],
          label: value[2],
          name: "", // or set to value[2] or another appropriate value
          uW: value[3] === 1,
          uG: value[4] === 1,
          oW: value[5] === 1,
          oG: value[6] === 1,
        };
      }
    }

    dispatch(setAnalogInputs(data)); // ✅ Redux direkt aktualisieren
    return data;
  }
);

// Redux Slice
const analogInputsSlice = createSlice({
  name: "analogInputsSlice",
  initialState,
  reducers: {
    setAnalogInput(
      state,
      action: PayloadAction<{ key: string; value: AnalogInput }>
    ) {
      state[action.payload.key] = action.payload.value;
    },
    setAnalogInputs(state, action: PayloadAction<Partial<AnalogInputsState>>) {
      Object.entries(action.payload).forEach(([key, value]) => {
        if (value) {
          state[key] = value;
        }
      });
    },
  },
  extraReducers: (builder) => {
    builder.addCase(loadFromWindow.fulfilled, (state, action) => {
      Object.assign(state, action.payload);
    });
  },
});

export const { setAnalogInput, setAnalogInputs } = analogInputsSlice.actions;

export default analogInputsSlice.reducer;
