/* globals sendIRCMessage */

import { test } from 'qunit';
import moduleForAcceptance from '../helpers/module-for-acceptance';
import channelScenario from 'web-client/mirage/scenarios/channel';
import ChannelPage from '../pages/channel';
import { stubLogin } from '../helpers/stub-login';
import { ircSocketMessages } from '../helpers/mock-web-sockets';

const channelName = 'twitch';
const username = 'friend';
const text = 'hello';
const regex = new RegExp(`.*#${channelName} :${text}`);

let page, messages;

moduleForAcceptance('Acceptance | Chat', {
  beforeEach() {
    channelScenario(this.server, channelName);
    page = ChannelPage.create({ name: channelName });
  }
});

test("logged-in normal user can send message on another user's channel page", function (assert) {
  assert.expect(2);

  stubLogin({ login: username });
  visit(page.url());

  page.fillInChat(text);

  andThen(() => {
    messages = ircSocketMessages();
    assert.equal(messages.length, 1, 'message sent to IRC URL');
    assert.ok(regex.test(messages[0].data), 'message sent with expected data format');
  });
});

test("logged-in normal user can receive chat message on another user's channel page", function (assert) {
  assert.expect(2);

  stubLogin({ username });

  visit(page.url());

  sendIRCMessage({
    from: username,
    channel: channelName,
    text: text
  });

  andThen(() => {
    assert.ok(page.hasFromName(), "IRC message contains sender's name");
    assert.ok(page.hasMessage(), "IRC message contains sender's message text");
  });
});

test('logged-in broadcaster can send message on own channel page', function (assert) {
  assert.expect(2);

  stubLogin({ username: channelName });
  visit(page.url());

  page.fillInChat(text);

  andThen(() => {
    messages = ircSocketMessages();
    assert.equal(messages.length, 1, 'message sent to IRC URL');
    assert.ok(regex.test(messages[0].data), 'message sent with expected data format');
  });
});

test('logged-in broadcaster can receive chat message on own channel page', function (assert) {
  assert.expect(2);

  stubLogin({ username: channelName });
  visit(page.url());

  sendIRCMessage({
    from: username,
    channel: channelName,
    text: text
  });

  andThen(() => {
    assert.ok(page.hasFromName(), "IRC message contains sender's name");
    assert.ok(page.hasMessage(), "IRC message contains sender's message text");
  });
});
