// Redux Slice: redux/slices/analogeEingaengeSlice.ts
import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";

export interface AnalogerEingang {
  id: number | null;
  value: number | null;
  name: string;
  uW: boolean;
  uG: boolean;
  oW: boolean;
  oG: boolean;
}

export interface AnalogeEingaengeState {
  [key: string]: AnalogerEingang;
}

// Standardwerte für Eingänge
const defaultAnalogerEingang: AnalogerEingang = {
  id: null,
  value: null,
  name: "",
  uW: false,
  uG: false,
  oW: false,
  oG: false,
};

// Initialer Zustand
const initialState: AnalogeEingaengeState = {
  win_analogeEingaenge1: { ...defaultAnalogerEingang },
  win_analogeEingaenge2: { ...defaultAnalogerEingang },
  win_analogeEingaenge3: { ...defaultAnalogerEingang },
  win_analogeEingaenge4: { ...defaultAnalogerEingang },
  win_analogeEingaenge5: { ...defaultAnalogerEingang },
  win_analogeEingaenge6: { ...defaultAnalogerEingang },
  win_analogeEingaenge7: { ...defaultAnalogerEingang },
  win_analogeEingaenge8: { ...defaultAnalogerEingang },
};

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

    for (let i = 1; i <= 8; i++) {
      const key = `win_analogeEingaenge${i}`;
      const value = (window as any)[key];

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

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

// Redux Slice
const analogeEingaengeSlice = createSlice({
  name: "analogeEingaengeSlice",
  initialState,
  reducers: {
    setAnalogerEingang(
      state,
      action: PayloadAction<{ key: string; value: AnalogerEingang }>
    ) {
      state[action.payload.key] = action.payload.value;
    },
    setAnalogeEingaenge(
      state,
      action: PayloadAction<Partial<AnalogeEingaengeState>>
    ) {
      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 { setAnalogerEingang, setAnalogeEingaenge } =
  analogeEingaengeSlice.actions;

export default analogeEingaengeSlice.reducer;
