import Ember from 'ember';
import store from 'corpus-common-addon/utils/store';
import * as constants from 'corpus-common-addon/utils/constants'
export default Ember.Service.extend({
env: function() {
return Ember.getOwner(this).resolveRegistration('config:environment')
},
_getStoreKey: function(id) {
return 'lexvo:'+id;
},
getName: function(id) {
if(!id) {
return new Ember.RSVP.Promise(function(resolve/*, reject*/) {
resolve("");
});
}
var lexvoId = id;
if(id.startsWith(constants.LEXVO_BASE_URL)) {
lexvoId = id.slice(constants.LEXVO_BASE_URL.length);
}
var namePromise = null;
var storeKey = this._getStoreKey(id);
var name = store.get(storeKey);
if(!name) {
//TODO: handle error !!!
namePromise = this.queryName(lexvoId)
.then( function(response) {
return store.set(storeKey, response);
});
}
else {
namePromise = new Ember.RSVP.Promise(function(resolve/*, reject*/) {
resolve(name);
});
}
return namePromise;
},
// make the query for the name.
// return a Promise
queryName: function(id) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
//TODO Configuration ?
url: this.env().baseURL.replace(/\/$/,"") + "/api/v1/lexvo/"+id,
success: function(lexvoDoc) {
var names = lexvoDoc.lexvoids;
resolve((id in names)?names[id]:null);
},
error: function(req, status, error) {
reject(status + ":" + error);
}
});
}.bind(this));
}
});