import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';
import { stringFormat, processStyling } from 'web-client/helpers/styled-i18n';
import EmberObject from 'ember-object';

moduleForComponent('bits-string', {
  integration: true,

  beforeEach() {
    this.fakeBitsStringsSvc = EmberObject.create({
      isLoaded: false,
      getString(key, defaultValue) {
        if (!this.get('isLoaded')) {
          return defaultValue;
        }
        return key;
      }
    });

    this.register('service:bits-strings', this.fakeBitsStringsSvc, { instantiate: false });
  }
});

test('returns default string if service hasnt loaded', function (assert) {
  assert.expect(1);

  this.fakeBitsStringsSvc.set('isLoaded', false);
  this.render(hbs`{{bits-string 'key' 'default_value'}}`);

  return wait().then(() => {
    assert.equal(this.$().text(), 'default_value');
  });
});

test('returns key value if service has loaded', function (assert) {
  assert.expect(1);

  this.fakeBitsStringsSvc.set('isLoaded', true);
  this.render(hbs`{{bits-string 'key' 'default_value'}}`);

  return wait().then(() => {
    assert.equal(this.$().text(), 'key');
  });
});

test('recompute', function (assert) {
  assert.expect(2);

  this.fakeBitsStringsSvc.set('isLoaded', false);
  this.render(hbs`{{bits-string 'key' 'default_value'}}`);

  return wait().then(() => {
    assert.equal(this.$().text(), 'default_value', 'default value');
    this.fakeBitsStringsSvc.set('isLoaded', true);

    return wait();
  }).then(() => {
    assert.equal(this.$().text(), 'key', 'suddenly the real value!');
  });
});

test('keys with styling and arguments', function (assert) {
  assert.expect(1);

  let styledValue = `$start-bold$%{balance} Bits$end-bold$`;

  // override the getString function
  this.fakeBitsStringsSvc.set('getString', () => {
    return styledValue;
  });

  this.fakeBitsStringsSvc.set('isLoaded', true);
  this.render(hbs`{{bits-string 'key' '' (hash balance=2)}}`);

  return wait().then(() => {
    styledValue = processStyling(styledValue);
    styledValue = stringFormat(styledValue, {balance: 2});
    assert.equal(this.$().html(), styledValue);
  });
});
