casper = require('./spec/spec_helper.js').Fantomas

casper.start('http://www.xmpp.dev/', ->
  @login()
)

#Click on the first person from the inactive list
casper.then(->
  @test.assertNotExists('#js-active-friends ul', 'Active list doesn\'t exists')
  inactiveListLengthBefore = @inactiveListLength()

  @click('#js-inactive-friends ul li:nth-child(2)')
  @echo 'Clicked on the first person in the inactive roster'

  inactiveListLengthAfter = @inactiveListLength()

  @test.assertExists('#conversation-js .conversation', 'Conversation window created')
  @test.assertExists('#js-tabbar .tab.active', 'Created new tab in the tabbar')
  @test.assert(inactiveListLengthBefore - 1 == inactiveListLengthAfter, 'User isn\'t in the inactive list')
  @test.assertExists('#js-active-friends ul li', 'User is in the active list')
)

#Click on another person from the inactive list
casper.then(->
  inactiveListLengthBefore = @inactiveListLength()

  @click('#js-inactive-friends ul li:nth-child(2)')
  @echo 'Clicked on the first person in the inactive roster'

  tabsLength = @tabsLength()

  activeListLength = @activeListLength()

  inactiveListLengthAfter = @inactiveListLength()

  @test.assert(tabsLength == 2, 'Number of opened tabs')
  @test.assert(activeListLength == 1, 'Length of the active list')
  @test.assert(inactiveListLengthBefore == inactiveListLengthAfter, 'Users from the active and the inactive list swapped')
)

#Test tab switching behaviour
casper.then(->
  for i in [1..2]
    @click("#js-tabbar .tab:nth-child(#{i}) a div")
    isActive = @evaluate((i)->
      __utils__.exists("#js-tabbar .tab:nth-child(#{i}).active")
    , i)
    @test.assert(isActive, 'Clicked tab is active')
)

#Test tab closing behaviour
casper.then(->
  @click('#js-tabbar .tab.active .js-close')
  @echo 'Closed active tab'

  @test.assertExists('#js-tabbar .tab.active', 'There\'s another active tab')
  @click('#js-tabbar .tab.active .js-close')
  @echo 'Closed another active tab'

  tabsLength = @tabsLength()
  activeListLength = @activeListLength()

  @test.assert(tabsLength == 0, 'No more tabs')
  @test.assert(activeListLength == 0, 'Nobody in active list')
)

casper.run(->
  @test.done()
  @test.renderResults(true)
)