import _ from 'lodash';
import { JOBS_LOADED, JOBS_REMOVED, JOBS_LOADING, JOBS_TYPES_LOADED, JOBS_STATUSES_LOADED, JOBS_HIDE_SEEN } from '../actions/types';
import { jobStatusOptions } from '../helper';

const INITIAL_STATE = {
  jobs: [],
  jobtypes: [],
  jobstatuses: jobStatusOptions,
  loading: false,
  hideSeen: false,
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case JOBS_LOADING:
      return { ...state, loading: true };
    case JOBS_LOADED:
      const result = _.unionWith(action.payload, state.jobs, (v1, v2) => {
        return v1 != null && v2 != null && v1.id === v2.id;
      });
      return {
        ...state,
        jobs: result.map((job) => ({ title: job.title || job.description, ...job })),
        loading: false,
      };
    case JOBS_REMOVED:
      const index = _.findIndex(state.jobs, (event) => {
        return event != null && event.id === action.payload;
      });
      if (index > -1) {
        const newJobs = [...state.jobs];
        newJobs.splice(index, 1);
        return { ...state, jobs: newJobs };
      }
      return state;
    case JOBS_TYPES_LOADED:
      const jobtypes = _.unionWith(action.payload, state.jobtypes, (v1, v2) => {
        return v1 != null && v2 != null && v1.id === v2.id;
      });
      return { ...state, jobtypes };
    case JOBS_STATUSES_LOADED:
      const jobstatuses = _.orderBy(action.payload, 'order', 'asc');
      return { ...state, jobstatuses };
    case JOBS_HIDE_SEEN:
      return { ...state, hideSeen: action.payload };
    default:
      return state;
  }
};
