import {
  selectNextWord,
  selectNextSentence,
  selectPrevWord,
  selectPrevSentence
} from './selectors'

export const initialState = {
  originalText: 'Sample Text',
  curIdx: 0,
  maxLength: 5,
  isPlaying: false,
  wpm: 300,
  running: false
}

const reducer = {
  SET_TEXT: (state, payload) => ({
    ...state,
    originalText: payload,
    curIdx: 0
  }),
  SET_CURRENT_SEGMENT: (state, payload) => ({ ...state, curIdx: payload }),
  INC_SEGMENT: state => ({ ...state, curIdx: state.curIdx + 1 }),
  DEC_SEGMENT: state => ({ ...state, curIdx: state.curIdx - 1 }),
  INC_WORD: state => ({ ...state, curIdx: selectNextWord(state) }),
  DEC_WORD: state => ({ ...state, curIdx: selectPrevWord(state) }),
  INC_SENTENCE: state => ({ ...state, curIdx: selectNextSentence(state) }),
  DEC_SENTENCE: state => ({ ...state, curIdx: selectPrevSentence(state) }),
  SET_MAX_LENGTH: (state, payload) => ({ ...state, maxLength: payload }),
  SET_WPM: (state, payload) => ({ ...state, wpm: payload }),
  START: state => ({ ...state, running: true }),
  STOP: state => ({ ...state, running: false, curIdx: 0 }),
  PAUSE: state => ({ ...state, running: false })
}

export const reducerFn = (state, { type, payload }) => {
  return reducer[type] ? reducer[type](state, payload) : state
}
