import { createReducer, Action, on } from '@ngrx/store';
import { INITIAL_TASK_FILES_STATE, TaskFilesState, taskFilesAdapter } from './task-files.state';
import * as actions from './task-files.actions';

const _taskFilesReducer = createReducer<TaskFilesState>(
  INITIAL_TASK_FILES_STATE,
  on(actions.clear, (s, a) =>
    taskFilesAdapter.removeMany(
      Object.values(s.entities)
        .filter((file) => file.taskId === a.taskId && file.section === a.section)
        .map((file) => file.id),
      s
    )
  ),
  on(actions.clearAll, (s) => taskFilesAdapter.removeAll(s)),
  on(actions.addFiles, (s, a) => taskFilesAdapter.addAll(a.files, s))
);

export function taskFilesReducer(state: TaskFilesState, action: Action) {
  return _taskFilesReducer(state, action);
}
