import Immutable from 'immutable'

import TagSuggest from '../presenter'

describe('TagSuggest', () => {
  const tags = [
    {id: '1', tag_value: 'waldo'}
  ]

  const props = {
    parentType: 'Bank',
    parentId: '0',
    tags,
    setTagInput: sinon.stub(),
    getTagSuggestions: sinon.stub(),
    setTagSuggestions: sinon.stub(),
    onChange: sinon.stub(),
  }
  const connectedTestbed = createTestbed(withContext(TagSuggest), props)

  let clock = null

  beforeEach(async () => {
    clock = sinon.useFakeTimers()
  })

  afterEach(async () => {
    clock.restore()
  })

  it('sets tag input on tag input change', async () => {
    connectedTestbed.render()
    const suggest = connectedTestbed.findChildrenByType(TagSuggest)
    suggest[0].handleTagInputChange('boo')
    expect(suggest[0].props.setTagInput).to.be.calledWith('Bank', '0', 'boo')
  })

  it('calls tag suggestion on tag input change', async () => {
    connectedTestbed.render()
    const suggest = connectedTestbed.findChildrenByType(TagSuggest)
    suggest[0].handleTagInputChange('boo')
    clock.tick(200)
    expect(suggest[0].props.getTagSuggestions)
      .to.be.calledWith('Bank', '0', 'boo')
  })

  it('does not get tag suggestion and resets null tag input', async () => {
    connectedTestbed.render()
    const suggest = connectedTestbed.findChildrenByType(TagSuggest)
    suggest[0].handleTagInputChange(null)
    clock.tick(200)
    expect(suggest[0].props.setTagSuggestions)
      .to.be.calledWith('Bank', '0', null)
  })

  it('proposes default suggestions on null input', async () => {
    connectedTestbed.render({
      defaultSuggestions: [
        { id: '1', value: 'boo' },
      ],
      tags: []
    })
    const suggest = connectedTestbed.findChildrenByType(TagSuggest)
    const suggestions = suggest[0].getTagSuggestions().toJS()
    expect(suggestions).to.deep.equal([
        { id: '1', value: 'boo' }
    ])
  })

  it('excludes tag suggestions for tags already selected', async () => {
    connectedTestbed.render({
      tagSuggestions: Immutable.fromJS([
        { id: '1', value: 'boo' },
        { id: '2', value: 'hey' }
      ]),
      tags: [
        { id: '1', value: 'boo' }
      ]
    })
    const suggest = connectedTestbed.findChildrenByType(TagSuggest)
    const suggestions = suggest[0].getTagSuggestions().toJS()
    expect(suggestions).to.deep.equal([
        { id: '2', value: 'hey' }
    ])
  })
})
