import ReactTestUtils from 'react-dom/test-utils'
import {List} from 'immutable'
import Errors from '../../../../../../../common/components/shared/errors/Errors'

import QuizTitleEdit from '../index'
import editableFieldTests from '../../../__tests__/editableFieldTests'

import styles from '../styles.css'

describe('Quiz Title Edit Presenter', () => {
  const styleClasses = {
    edit_input: styles.titleEditInput
  }
  const QuizTitleEditWithContext = withContext(QuizTitleEdit)

  // shared tests with QuizInstructionsEdit
  editableFieldTests(QuizTitleEditWithContext)

  const testbed = createTestbed(QuizTitleEditWithContext, {
    hideError: () => {},
    isValid: true,
    saveAndPreview: () => {},
    showError: () => {}
  })

  it('should show Errors if errorsAreShowing is true and chocies have errors', () => {
    testbed.render({
      errorsAreShowing: true,
      errors: List('something is wrong')
    })

    const errorBorder = testbed.findChildrenByClass(styles.errorBorder)[0]
    expect(errorBorder).to.not.be.undefined()

    const errorList = testbed.findChildrenByType(Errors)[0]
    expect(errorList).to.not.be.undefined()
  })

  it('should call saveAndPreview when blurred', () => {
    // make test synchronous
    const fakeDefer = (fn) => {
      document.activeElement.blur()
      fn()
    }

    const saveAndPreviewSpy = sinon.spy()
    testbed.render({
      deferMock: fakeDefer,
      saveAndPreview: saveAndPreviewSpy
    })

    document.activeElement.blur()
    expect(saveAndPreviewSpy).to.have.been.calledOnce()
  })

  it('should call showError on blur when invalid', () => {
    // make test synchronous
    const fakeDefer = (fn) => {
      document.activeElement.blur()
      fn()
    }

    const showErrorStub = sinon.stub()
    testbed.render({
      isValid: false,
      deferMock: fakeDefer,
      showError: showErrorStub
    })

    document.activeElement.blur()
    expect(showErrorStub).to.have.been.calledOnce()
  })

  it('editing the input calls the onInputChange prop', () => {
    const onChangeSpy = sinon.spy()
    testbed.render({
      onInputChange: onChangeSpy
    })

    const titleInput = testbed.findChildrenByClass(styleClasses.edit_input)[0]
    ReactTestUtils.Simulate.change(titleInput)

    expect(onChangeSpy.called).to.be.true()
  })

  it('keying down on the input calls the onInputKeyDown prop', () => {
    const onKeyDownSpy = sinon.spy()
    testbed.render({
      onInputKeyDown: onKeyDownSpy
    })

    const titleInput = testbed.findChildrenByClass(styleClasses.edit_input)[0]
    ReactTestUtils.Simulate.keyDown(titleInput)

    expect(onKeyDownSpy.called).to.be.true()
  })
})
