import { fromJS } from 'immutable'
import { expect } from 'chai'

import Fetcher from '../../../common/util/Fetcher'
import { getQuizSessionEvents } from '../quizSessionEvents'
import {addQuizSessionEvents} from '../../../common/actions/quizSessionEvents'

import makeFakeFetch from '../../../../tests/util/fakeFetch'
import {jsoniblePromise} from '../../../common/util/jsonify'

describe('getQuizSessionEvents', () => {
  const dispatchStub = sinon.stub()
  const getStateStub = sinon.stub().returns(fromJS(
    {quizSessionEvents: {}}
  ))
  const fetchStub = sinon.stub()
  useFakeFetching({dispatchStub, getStateStub, fetchStub})

  const quizSessionId = '123'
  const stubbedGetQuizSessionEventsCall = () => {
    Fetcher.fakeFetch = fetchStub
    const getQuizSessionEventsThunk = getQuizSessionEvents(quizSessionId)
    getQuizSessionEventsThunk(dispatchStub, getStateStub)
  }

  it('should hit the right endpoint', () => {
    stubbedGetQuizSessionEventsCall()
    expect(
      fetchStub.calledWith(
        `/api/quiz_sessions/${quizSessionId}/quiz_session_events?`
      )
    ).to.be.true()
  })

  it('should persist quiz session event data', (done) => {
    const quizSessionEventsRes = jsoniblePromise([
      {created_at: 'someValue'}
    ])
    const fakeFetch = makeFakeFetch(quizSessionEventsRes)

    Fetcher.fakeFetch = fakeFetch
    const getQuizSessionEventsThunk = getQuizSessionEvents(quizSessionId)
    const fetchPromise = getQuizSessionEventsThunk(dispatchStub, getStateStub)
    const expectedAction = addQuizSessionEvents([{createdAt: 'someValue'}])

    fetchPromise.then(() => {
      checkActionDispatched(dispatchStub, expectedAction)
      done()
    })
  })
})
