import ReactDOM from 'react-dom'
import ReactTestUtils from 'react-dom/test-utils'
import Button from '@instructure/ui-buttons/lib/components/Button'

import mouseEventOn from '../../../../../../../../tests/util/mouseEventOn'
import editableFieldTests from '../../../__tests__/editableFieldTests'

import QuizInstructionsEdit from '../presenter'

describe('QuizInstructionsEdit', () => {
  // shared tests with QuizTitleEdit
  editableFieldTests(QuizInstructionsEdit)

  const saveAndPreviewStub = sinon.stub()
  const endEditingStub = sinon.stub()
  const testbed = createTestbed(withContext(QuizInstructionsEdit), {
    endEditing: endEditingStub,
    inputValue: 'foo',
    onInputChange () {},
    quizId: '42',
    saveAndPreview: saveAndPreviewStub,
    appContainer: '.root'
  })

  afterEach(() => {
    saveAndPreviewStub.resetHistory()
    endEditingStub.resetHistory()
  })

  it('calls saveAndPreview on click outside', () => {
    testbed.render()
    const outerElement = document.createElement('div')
    outerElement.className = 'root'
    document.body.appendChild(outerElement)
    mouseEventOn(outerElement, 'click')
    expect(saveAndPreviewStub).to.have.been.calledOnce()
  })

  it('calls saveAndPreview when clicked Done', () => {
    testbed.render()
    const doneButton = ReactDOM.findDOMNode(testbed.findChildrenByType(Button)[2])
    expect(doneButton.innerText).to.include('Done')
    ReactTestUtils.Simulate.click(doneButton)
    expect(saveAndPreviewStub).to.have.been.called()
  })

  it('calls endEditing when clicked Cancel', () => {
    testbed.render()
    const cancelButton = ReactDOM.findDOMNode(testbed.findChildrenByType(Button)[1])
    expect(cancelButton.innerText).to.include('Cancel')
    ReactTestUtils.Simulate.click(cancelButton)
    expect(endEditingStub).to.have.been.called()
    expect(saveAndPreviewStub).to.have.not.been.called()
  })
})
