import { fromJS } from 'immutable'
import { expect } from 'chai'
import keyBy from 'lodash/keyBy'

import { ADD_QUIZ_SESSION_RESULTS } from '@instructure/quiz-common/lib/constants'
import quizSessionResults from '../quizSessionResults'
import { fakeSessionItemResults, fakeSessionItemResults2 } from '../../../../tests/util/fakeSessionItemResults'

describe('quiz session result', () => {
  describe('#addQuizSessionResult', () => {
    it('adds a quizSessionResult to the store with ADD_QUIZ_SESSION_RESULT', () => {
      const mockAction = {type: ADD_QUIZ_SESSION_RESULTS, payload: fakeSessionItemResults}
      const quizSessionResultsHash = keyBy(mockAction.payload, 'id')
      const newState = quizSessionResults(void 0, mockAction)

      expect(newState).to.deep.equal(fromJS(quizSessionResultsHash))
    })

    it('adds a result to the list when stored', () => {
      const mockAction = {type: ADD_QUIZ_SESSION_RESULTS, payload: fakeSessionItemResults}
      const mockAction2 = {type: ADD_QUIZ_SESSION_RESULTS, payload: fakeSessionItemResults2}

      const newState = quizSessionResults(fromJS({}), mockAction)
      const newState2 = quizSessionResults(newState, mockAction2)

      const expectResult = fakeSessionItemResults.concat(fakeSessionItemResults2)
      expect(newState2).to.deep.equal(fromJS(keyBy(expectResult, 'id')))
    })

    it('deeply merges new quiz session results', () => {
      const completeResult = {
        id: '1', sessionItemResults: ['1', '2']
      }
      const incompleteResult = {id: '1'}

      const completeInfoAction = {type: ADD_QUIZ_SESSION_RESULTS, payload: [completeResult]}
      const incompleteInfoAction = {type: ADD_QUIZ_SESSION_RESULTS, payload: [incompleteResult]}

      const stateOne = quizSessionResults(fromJS({}), completeInfoAction)
      const stateTwo = quizSessionResults(stateOne, incompleteInfoAction)

      expect(stateTwo.getIn(['1', 'sessionItemResults']))
        .to.deep.equal(fromJS(['1', '2']))
    })
  })
})
