import { createSelector } from 'reselect'
import { parseText } from '../lib/parseText'

import { getNextBiggerNumber, getNextSmallerNumber } from '../lib/array-util.js'

// parsedText selectors

export const selectMaxLength = state => state.maxLength

export const selectParsedText = createSelector(
  state => state.originalText,
  selectMaxLength,
  (originalText, maxLength) => parseText(originalText, maxLength)
)

export const selectSegments = createSelector(
  selectParsedText,
  parsedText => parsedText.segments
)

export const selectCurrentSegmentIndex = state => state.curIdx

export const selectCurrentSegment = createSelector(
  selectParsedText,
  selectCurrentSegmentIndex,
  (parsedText, curIdx) => parsedText.segments[curIdx]
)

export const hasNextSegment = createSelector(
  selectSegments,
  selectCurrentSegmentIndex,
  (segments, idx) => {
    return idx < segments.length - 1
  }
)

// next/prev words

export const selectWords = createSelector(
  selectParsedText,
  parsedText => parsedText.words
)

export const selectNextWord = createSelector(
  selectWords,
  selectCurrentSegmentIndex,
  (words, curSegment) => getNextBiggerNumber(curSegment, words)
)

export const selectPrevWord = createSelector(
  selectWords,
  selectCurrentSegmentIndex,
  (words, curSegment) => getNextSmallerNumber(curSegment, words)
)

export const selectHasNextWord = createSelector(selectNextWord, Boolean)
export const selectHasPrevWord = createSelector(selectPrevWord, Boolean)

// next/prev sentences

export const selectSentences = createSelector(
  selectParsedText,
  parsedText => parsedText.sentences
)

export const selectNextSentence = createSelector(
  selectSentences,
  selectCurrentSegmentIndex,
  (sentences, curSegment) => getNextBiggerNumber(curSegment, sentences)
)

export const selectPrevSentence = createSelector(
  selectSentences,
  selectCurrentSegmentIndex,
  (sentences, curSegment) => getNextSmallerNumber(curSegment, sentences)
)

export const selectHasNextSentence = createSelector(selectNextSentence, Boolean)
export const selectHasPrevSentence = createSelector(selectPrevSentence, Boolean)

export const selectRunning = state => state.running
export const selectWpm = state => state.wpm
export const selectInterval = createSelector(selectWpm, wpm => 60000 / wpm)
