import moduleForComponent from 'web-client/tests/helpers/module-for-component';
import { test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';

moduleForComponent('manager/create-video-form', 'Integration | Component | manager/create-video-form', {
  beforeEach() {
    this.channel = this.server.create('channel');
  }
});

test("saves the video when submitted", function(assert) {
  assert.expect(4);

  this.set('channelName', this.channel.name);
  this.set('file', { name: 'dummy-file' });

  let onSubmitArgs;
  this.set('onSubmit', (...args) => {
    onSubmitArgs = args;
  });

  this.render(hbs`{{manager/create-video-form video=video onSubmit=onSubmit channelName=channelName file=file}}`);

  this.$('[data-test-upload-edit]').click();

  return wait().then(() => {
    assert.equal(this.server.schema.videos.all().models.length, 1, "created one video");

    let video = this.server.schema.videos.first();
    assert.equal(video.title, 'dummy file', 'names the video according to the file title');
    assert.equal(onSubmitArgs[0].id, video.id, 'onSubmit called with video');
    assert.equal(onSubmitArgs[1], this.get('file'), 'onSubmit called with file');
  });
});

test("shows an error message when server returns an error", function(assert) {
  assert.expect(2);

  this.set('file', { name: 'dummy-file' });

  let onSubmitCallCount = 0;
  this.set('onSubmit', () => {
    onSubmitCallCount++;
  });

  this.server.post('https://api.twitch.tv/kraken/videos', { message: 'error-message' }, 500);

  this.render(hbs`{{manager/create-video-form video=video onSubmit=onSubmit file=file}}`);

  this.$('[data-test-upload-edit]').click();

  return wait().then(() => {
    assert.equal(this.$('[data-test-error-message]').text().trim(), 'error-message', 'Shows an error message to the user');
    assert.equal(onSubmitCallCount, 0, 'onSubmit is not called');
  });
});
