import { createSlice } from "@reduxjs/toolkit";

export const uploadSlice = createSlice({
  name: "upload",
  initialState: {
    uploading: [],
    result: {
      success: [],
      failed: [],
    },
  },
  reducers: {
    setUploading: (state, action) => {
      state.uploading = action.payload;
    },

    addUploading: (state, action) => {
      if (Array.isArray(action.payload)) {
        state.uploading.push(...action.payload);
        return;
      }

      state.uploading.push(action.payload);
    },

    updateProgressById: (state, action) => {
      const index = Array.from(state.uploading).findIndex(
        (item) => item.tempId === action.payload.tempId
      );

      state.uploading[index] = { ...state.uploading[index], ...action.payload };
    },

    updateUploadingById: (state, action) => {
      const index = Array.from(state.uploading).findIndex(
        (item) => item.tempId === action.payload.tempId
      );

      state.uploading[index] = action.payload;
    },

    setFailed: (state, action) => {
      state.result.failed = action.payload;
    },

    addSuccess: (state, action) => {
      const data = Array.isArray(action.payload)
        ? action.payload
        : [action.payload];

      state.result.success = [...state.result.success, ...data];
    },

    clearResult: (state) => {
      state.result = {
        success: [],
        failed: [],
      };
    },
  },
  selectors: {
    selectUploading: (state) => state.uploading,
    selectResult: (state) => state.result,
  },
});

export const {
  setUploading,
  addUploading,
  updateProgressById,
  updateUploadingById,
  setFailed,
  addSuccess,
  clearResult,
} = uploadSlice.actions;
export const { selectUploading, selectResult } = uploadSlice.selectors;

export default uploadSlice.reducer;
