/* eslint-disable no-param-reassign */
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { main } from '@wailsapp/go/models';

export interface ProcessedLogEntry {
  id: string;
  time: Date;
  level: string;
  message: string;
  data: object;
}

export function processEntry({
  id,
  time,
  level,
  message,
  data,
}: main.LogEntry): ProcessedLogEntry {
  return {
    id,
    time: new Date(time),
    level,
    message,
    data: JSON.parse(data) as object,
  };
}

interface LoggingState {
  messages: ProcessedLogEntry[];
}

const initialState: LoggingState = {
  messages: [],
};

const keyfn = (ev: main.LogEntry) => ev.id;

const loggingReducer = createSlice({
  name: 'logging',
  initialState,
  reducers: {
    loadedLogData(state, { payload }: PayloadAction<main.LogEntry[]>) {
      const logKeys = payload.map(keyfn);

      // Clean up duplicates before setting to state
      const uniqueLogs = payload.filter(
        (ev, pos) => logKeys.indexOf(keyfn(ev)) === pos,
      );

      state.messages = uniqueLogs
        .map(processEntry)
        .sort((a, b) => a.time.getTime() - b.time.getTime());
    },
    receivedEvent(state, { payload }: PayloadAction<main.LogEntry>) {
      state.messages.push(processEntry(payload));
    },
    clearedEvents(state) {
      state.messages = [];
    },
  },
});

export default loggingReducer;
