/* globals i18n */

/*
  This component will be deprecated in favor of the new {{game-select}}
  component. -Brian Chan
*/

import Component from 'ember-component';
import run from 'ember-runloop';
import $ from 'jquery';

export default Component.extend({
  placeholder: i18n('Search for a game'),
  value: '',
  previousValue: '',
  onGameChange: null,

  didInsertElement() {
    this._super(...arguments);
    $('#gameselector_input').gameselector($('#gameTmpl'), {
      loadAsDisabled: false,
      actionFn: run.bind(this, (game) => {
        if (this.isDestroyed) { return; }

        this.set('value', game);

        let onGameChange = this.get('onGameChange');
        if (onGameChange) {
          onGameChange(game);
        }

        let action = this.get('handleGameClick');
        if (action) {
          action({id: game});
        }
      })
    });
  },

  actions: {
    onFocus() {
      this.set('previousValue', this.get('value'));
    },
    onBlur() {
      let onGameChange = this.get('onGameChange');
      let value = this.get('value');
      if (onGameChange && value !== this.get('previousValue')) {
        onGameChange(value);
      }
    }
  }
});
