import ReportingActionTypes from "./reporting.types";
const INITIAL_STATE = {
  dates: { startDate: null, endDate: null },
  data: [],
  scoreCard: null,
  error: null,
  loading: false,
  auditLoading: false,
  audit: {},
  auditError: null,
  excludedIds: [],
  cachedJobs: []
};

const applicationReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case ReportingActionTypes.QUERY_REPORTING_DATA:
      return {
        ...state,
        loading: true,
        error: null,
        dates: {
          startDate: action.payload.startDate.toISOString(),
          endDate: action.payload.endDate.toISOString()
        }
      };
    case ReportingActionTypes.SET_REPORTING_ERROR:
      return {
        ...state,
        error: action.payload
      };
    case ReportingActionTypes.SET_REPORTING_DATA:
      return { ...state, data: action.payload };
    case ReportingActionTypes.SET_SCORE_CARD:
      return { ...state, loading: false, scoreCard: action.payload };
    case ReportingActionTypes.CALCULATE_AUDIT:
      return { ...state, auditLoading: true };
    case ReportingActionTypes.SET_AUDIT_RESULTS:
      return { ...state, loading: false, auditLoading: false, auditError: null, audit: action.payload };
    case ReportingActionTypes.SET_AUDIT_ERROR:
      return { ...state, auditLoading: false, auditError: action.payload };
    case ReportingActionTypes.ADD_EXCLUDED_ID:
      return { ...state, excludedIds: [...state.excludedIds, action.payload] };
    case ReportingActionTypes.REMOVE_EXCLUDED_ID:
      return { ...state, excludedIds: state.excludedIds.filter((id) => id !== action.payload) };
    case ReportingActionTypes.CLEAR_EXCLUDED_IDS:
      return { ...state, excludedIds: [] };
    case ReportingActionTypes.SET_CACHED_JOBS:
      return { ...state, cachedJobs: action.payload };
    case ReportingActionTypes.TOGGLE_GROUP_VERIFIED:
      return {
        ...state,
        data: state.data.map((d) => {
          if (d.id === action.payload) {
            return { ...d, group_verified: !d.group_verified };
          } else {
            return d;
          }
        })
      };
    case ReportingActionTypes.TOGGLE_SGI_RCC:
      return {
        ...state,
        data: state.data.map((d) => {
          if (d.id === action.payload) {
            return { ...d, sgi_rcc: !d.sgi_rcc };
          } else {
            return d;
          }
        })
      };
    default:
      return state;
  }
};

export default applicationReducer;
