import Ember from 'ember';
import URI from 'urijs';
import suggestionTemplate from 'bo-client/templates/components/bo-doc-bnf-autocomplete/suggestion';
import notFoundTemplate from 'bo-client/templates/components/bo-doc-bnf-autocomplete/notFound';
import pendingTemplate from 'bo-client/templates/components/bo-doc-bnf-autocomplete/pending';
import _ from 'lodash/lodash';
import config from 'bo-client/config/environment';
import * as utils from 'corpus-common-addon/utils/utils';
import * as constants from 'corpus-common-addon/utils/constants';

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

export default Ember.Component.extend({
  actions: {
    setBnfId: function(value) {
      if(_.isString(value) && utils.isArkBnfLink(value)) {
        this.set('bnfId', {
          label: null,
          url: value
        });
      }
      else if (value) {
        if(utils.isBnfLink(value.url)) {
          var bnfFrId = value.url.slice(constants.BNF_BASE_URL.length);
          var query = "SELECT ?s WHERE { ?s <http://data.bnf.fr/ontology/bnf-onto/FRBNF> \""+bnfFrId+"\"^^<http://www.w3.org/2001/XMLSchema#integer> }";
          var url = URI(config.APP['bo-doc-bnf-autocomplete'].bnfSparqlUrl).query({query: query, format: "application/sparql-results+json"}).toString();
          var _this = this;
          Ember.$.getJSON(url, function(data) {
            _this.set('bnfId', {
              label: value.label,
              url: data.results.bindings[0].s.value
            });
          });
        }
      }
    },
  },

  limit: 15,

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

  setValue() {
    return;
  },

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

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


  bnfSource : function(query, syncResults, asyncResults) {
    //var url = URI().query({term: query}).toString();
    if(!query || query.length < 4 || query.match(/http?:?/)) {
      syncResults(null);
      return;
    }
    var url = URI(config.APP['bo-doc-bnf-autocomplete'].bnfQueryUrl).query({term: query}).toString();
    Ember.$.ajax({
      url: url,
      dataType: "json",
      jsonp: false,
      success: function(data) {
        if (data) {
          var results = _(data).filter(function(r) {
            return r.raw_category === 'Rameau';
          }).map(function(r) {
            return {
              label: r.label,
              url: r.value
            };
          }).value();
          asyncResults( results );
        } else {
          asyncResults([]);
        }
      },
      error: function(/*jqXHR, textStatus, errorThrown*/) {
        //console.log("ERROR", jqXHR, textStatus, errorThrown);
      }
    });
  }

});
