import { Action, createReducer, on } from '@ngrx/store';
import { TaskCalendarState, INITIAL_TASK_CALENDAR_STATE, taskCalendarAdapter } from './task-calendar.state';
import * as actions from './task-calendar.actions';
import { DisplayInfoRequest } from '@swagger/eis';

const _taskCalendarReducer = createReducer<TaskCalendarState>(
  INITIAL_TASK_CALENDAR_STATE,
  on(actions.getTasksRequest, (s): TaskCalendarState => ({ ...s, fetching: true })),
  on(actions.getTasksResponse, (s): TaskCalendarState => ({ ...s, fetching: false })),
  on(actions.setTasks, (s, a): TaskCalendarState => taskCalendarAdapter.addAll(a.tasks, s)),
  on(actions.setFilter, (s, a): TaskCalendarState => ({ ...s, filter: a.filter })),
  on(actions.patchFilter, (s, a): TaskCalendarState => ({ ...s, filter: { ...(s.filter || ({} as DisplayInfoRequest)), ...a.filter } })),
  on(actions.patchTask, (s, a): TaskCalendarState => taskCalendarAdapter.updateOne({ id: a.taskId, changes: a.changes }, s))
);

export function taskCalendarReducer(state: TaskCalendarState, action: Action) {
  return _taskCalendarReducer(state, action);
}
