import Ember from 'ember';
import { moduleFor } from 'ember-qunit';
import test from 'ember-sinon-qunit/test-support/test';
import wait from 'ember-test-helpers/wait';
import {
  setup as setupMirage, teardown as teardownMirage
} from '../../helpers/setup-mirage-for-integration';
import { camelize } from 'ember-string';

const { pluralize } = Ember.String;

let adapter;

moduleFor('adapter:presence', 'Integration | Adapter | presence', {
  needs: ['service:session', 'service:twitch-presence/backend/ajax'],
  beforeEach() {
    setupMirage(this);
    adapter = this.subject();
  },
  afterEach() {
    teardownMirage(this);
  }
});

test('pathForType - strips addon prefix', function (assert) {
  let name = 'foo';
  let path = adapter.pathForType(name);

  assert.equal(path, pluralize(name), 'prefix stripped');

  return wait();
});

test('pathForType - still camelCases and pluralizes as expected', function (assert) {
  let name = 'foo-bar';
  let path = adapter.pathForType(name);

  assert.equal(path, pluralize(camelize(name)), 'correct path returned');

  return wait();
});

test('pathForType - defaults to regular behavior if no prefix', function (assert) {
  let name = 'foo';
  let path = adapter.pathForType(name);

  assert.equal(path, pluralize(name), 'correct path returned');

  return wait();
});

test('ajax - no type', function (assert) {
  let ajaxService = adapter.get('ajaxService');
  let foo = 'foo';
  let stub = this.stub(ajaxService, '_request', function () {
    return foo;
  });

  let url = 'bar';
  let options = {};

  let result = adapter.ajax(url, null, options);

  assert.ok(stub.calledOnce, '_request was called once');
  let { args } = stub.firstCall;
  assert.equal(args.length, 2, '2 args passed to _request');
  assert.equal(args[0], url, 'url passed to _request');
  assert.equal(args[1], options, 'options passed to _request');
  assert.equal(result, foo, 'returns the result of _request');

  return wait();
});

test('ajax - with type', function (assert) {
  let ajaxService = adapter.get('ajaxService');
  let foo = 'foo';
  let stub = this.stub(ajaxService, '_request', function () {
    return foo;
  });

  let url = 'bar';
  let type = 'GET';
  let options = { data: 'stuff' };

  adapter.ajax(url, type, options);

  let { args } = stub.firstCall;
  assert.equal(args.length, 2, '2 args passed to _request');
  assert.equal(args[1].data, options.data, 'existing options preserved');
  assert.equal(args[1].type, type, 'type added to options');

  return wait();
});
