import EmberObject from 'ember-object';
import moduleForComponent from 'web-client/tests/helpers/module-for-component';
import Ember from 'ember';
import { test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import { TIMESTAMP_INTERVAL } from 'web-client/helpers/twitch-conversations/show-timestamp';

const { A: emberA, run } = Ember;

const DEFAULT_TEMPLATE = hbs`
{{#each allMessages as |currentMessage|~}}
  [{{~if
    (twitch-conversations/show-timestamp allMessages currentMessage)
    'true'
    'false'
  ~}}]
{{~/each}}`;

const FakeMessage = EmberObject.extend();

moduleForComponent('twitch-conversations/show-timestamp', 'helper:conversations/show-timestamp', {
  beforeEach() {
    this.addMessage = (body, forceTimestamp=false) => {
      let messages = this.get('allMessages');
      let lastMessageTime = messages.get('lastObject.sentAt') || 0;

      let sentAt = lastMessageTime + TIMESTAMP_INTERVAL - 100;

      if (forceTimestamp) {
        sentAt += 1000;
      }

      run(() => {
        messages.pushObject(FakeMessage.create({body, sentAt}));
      });
    };

    this.set('allMessages', emberA());
    this.addMessage('first message');
    this.addMessage('second message');
    this.addMessage('third message', true);
  }
});


test('initial calculation works properly', function (assert) {
  this.render(DEFAULT_TEMPLATE);

  assert.equal(this.$().text().trim(), '[true][false][true]');
});

test('adding new item within timestamp window does not show timestamp', function (assert) {
  this.render(DEFAULT_TEMPLATE);

  this.addMessage('new item', false);

  assert.equal(this.$().text().trim(), '[true][false][true][false]');
});

test('adding new item beyond timestamp window shows a timestamp', function (assert) {
  this.render(DEFAULT_TEMPLATE);

  this.addMessage('new item', true);

  assert.equal(this.$().text().trim(), '[true][false][true][true]');
});
