import { INITIAL_TASK_ARTICLES_STATE, TaskArticlesState, taskArticlesAdapter } from './task-articles.state';
import { createReducer, Action, on } from '@ngrx/store';
import * as actions from './task-articles.actions';

const _taskArticlesReducer = createReducer<TaskArticlesState>(
  INITIAL_TASK_ARTICLES_STATE,
  on(actions.clear, (s, a) =>
    taskArticlesAdapter.removeMany(
      Object.values(s.entities)
        .filter((f) => f.taskId === a.taskId)
        .map((article) => article.id),
      s
    )
  ),
  on(actions.clearAll, (s) => taskArticlesAdapter.removeAll(s)),
  on(actions.addArticles, (s, a) => taskArticlesAdapter.addMany(a.articles, s))
);

export function taskArticlesReducer(state: TaskArticlesState, action: Action) {
  return _taskArticlesReducer(state, action);
}
