import config from 'bo-client/config/environment';
import suggestionTemplate from 'bo-client/templates/components/bo-doc-viaf-autocomplete/suggestion';
import notFoundTemplate from 'bo-client/templates/components/bo-doc-viaf-autocomplete/notFound';
import pendingTemplate from 'bo-client/templates/components/bo-doc-viaf-autocomplete/pending';
import Ember from 'ember';
import URI from 'urijs';
import _ from 'lodash/lodash';


//const suggestionTemplateBase = _.template('<div class="typeahead-suggestion""><% if(model) { %><%= model.label %> - <%= model.url %><% } %></div>');

// inspired by https://github.com/oclc-developer-house/jquery-viaf-autocomplete/blob/master/src/jquery.viafauto.js
/*jshint unused:false*/
export default Ember.Component.extend({

  actions: {
    setViafId: function(value) {
      if(_.isString(value)) {
        this.set('viafId', {
          label: value,
          value: value,
          id: "",
          url: "",
          nametype: "" }
        );
      }
      else {
        this.set('viafId', value);
      }
    },
  },

  limit: 15,

  display(selection) {
    return selection.value;
  },

  setValue(selection) {
    let typeahead = Ember.$(this.$(), ".aupac-typeahead");
    if(selection) {
      if(_.isString(selection)) {
        typeahead.typeahead('val', selection);
      } else {
        typeahead.typeahead('val', selection.value);
      }

    } else {
      typeahead.typeahead('val', '');
    }
  },

  keyDown(event) {
    if(event.which === this.get('constants').KEY_CODES.RETURN) {
      Ember.$(this.$(), ".aupac-typeahead").typeahead('close');
    }
  },

  //suggestionTemplate: (model) => { return suggestionTemplateBase({model: model}); },
  suggestionTemplate: suggestionTemplate,
  notFoundTemplate: notFoundTemplate,
  pendingTemplate: pendingTemplate,

  _registerAfterRender: function() {
    Ember.run.schedule('afterRender', this, function () {
      this.set('registerAs', this);
    });
  }.on('init'),


  viafSource : function(query, syncResults, asyncResults) {
    var url = URI(config.APP['bo-doc-viaf-autocomplete'].viafQueryUrl).query({query: query}).toString();
    Ember.$.ajax({
      url: url,
      dataType: "jsonp",
      success: function(data) {
        var queryTextRes = {
          label: query,
          value: query,
          id: "",
          url: "",
          nametype: ""
        };
        if (data.result) {
          var results = Ember.$.map( data.result, function(item) {
            var retLbl = item.term + " [" + item.nametype + "]",
                viafurl = config.APP['bo-doc-viaf-autocomplete'].viafBaseUrl + item.viafid;
            return {
              label: retLbl,
              value: item.term,
              id: item.viafid,
              url: viafurl,
              nametype: item.nametype
            };
          });
          results.unshift(queryTextRes);
          asyncResults( results );
        } else {
          asyncResults([queryTextRes]);
        }
      },
    });
  }
});
