import ReactTestUtils from 'react-dom/test-utils'
import IconClock from '@instructure/ui-icons/lib/Line/IconClock'

import ConnectedTimer from '../index'
import Timer from '../presenter'
import FormattedDuration from '../../../../shared/FormattedDuration'


describe('Timer component', () => {
  const updateTimerMinimizedStub = sinon.stub()
  const screenreaderNotificationStub = sinon.stub()
  const testbed = createTestbed(Timer, {
    screenreaderNotification: screenreaderNotificationStub,
    updateTimerMinimized: updateTimerMinimizedStub,
    timerRunning: true
  })

  afterEach(() => {
    screenreaderNotificationStub.resetHistory()
    updateTimerMinimizedStub.resetHistory()
  })

  it('renders with nothing when timerRunning is false', () => {
    testbed.render({timerRunning: false})
    const results = testbed.findChildrenByType(FormattedDuration)
    expect(results.length).to.eq(0)
  })

  it('renders with a formatted duration when timerRunning is true', () => {
    testbed.render({timeLeftInSeconds: 100})
    const results = testbed.findChildrenByType(FormattedDuration)
    expect(results.length).to.eq(1)
  })

  it('renders with an icon when timer is running and minimized', () => {
    testbed.render({timerRunning: true, timeLeftInSeconds: 100, timerMinimized: true})
    const icon = testbed.findChildrenByType(IconClock)[0]
    expect(icon).to.not.be.undefined()
  })

  it('minimizes the timer when currently maximized', () => {
    testbed.render({timerMinimized: false})
    const button = testbed.findChildrenByTagName('button')[0]
    ReactTestUtils.Simulate.click(button)
    expect(updateTimerMinimizedStub.calledWith(true)).to.be.true()
  })

  it('maximizes the timer when currently minimized', () => {
    testbed.render({timerMinimized: true})
    const button = testbed.findChildrenByTagName('button')[0]
    ReactTestUtils.Simulate.click(button)
    expect(updateTimerMinimizedStub.calledWith(false)).to.be.true()
  })

  it('calls the screenreader and refocuses when timerMinimized changes', () => {
    testbed.render({timerMinimized: false})
    const focusOnShowStub = sinon.stub(testbed.subject, 'focusOnShow')
    const focusOnHideStub = sinon.stub(testbed.subject, 'focusOnHide')

    expect(screenreaderNotificationStub.called).to.be.false()

    testbed.render({timerMinimized: true})
    expect(screenreaderNotificationStub.calledWith('timer minimized')).to.be.true()
    expect(focusOnShowStub.called).to.be.true()

    testbed.render({timerMinimized: false})
    expect(screenreaderNotificationStub.calledWith('timer showing')).to.be.true()
    expect(focusOnHideStub.called).to.be.true()

    testbed.subject.focusOnShow.resetHistory()
    testbed.subject.focusOnHide.resetHistory()
  })

  describe('test with connect', () => {
    const connectedTestbed = createTestbed(
      withContext(ConnectedTimer),
      {}
    )

    shouldRenderComponent(
      connectedTestbed, {}, Timer
    )
  })
})
