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 'bnf:'+id;
},
getLabel: function(id) {
if(!id) {
return new Ember.RSVP.Promise(function(resolve/*, reject*/) {
resolve("");
});
}
var bnfId = id;
if(id.startsWith(constants.BNF_BASE_URL + constants.BNF_ARK_BASE_ID)) {
bnfId = id.slice((constants.BNF_BASE_URL + constants.BNF_ARK_BASE_ID).length);
}
else if (id.startsWith(constants.BNF_ARK_BASE_URL + constants.BNF_ARK_BASE_ID)) {
bnfId = id.slice((constants.BNF_ARK_BASE_URL + constants.BNF_ARK_BASE_ID).length);
}
else if (id.startsWith(constants.BNF_ARK_BASE_ID)) {
bnfId = id.slice(constants.BNF_ARK_BASE_ID.length);
}
var labelPromise = null;
var storeKey = this._getStoreKey(id);
var label = store.get(storeKey);
if(!label) {
//TODO: handle error !!!
labelPromise = this.queryLabel(bnfId)
.then( function(response) {
return store.set(storeKey, response);
});
}
else {
labelPromise = new Ember.RSVP.Promise(function(resolve/*, reject*/) {
resolve(label);
});
}
return labelPromise;
},
// make the query for the name.
// return a Promise
queryLabel: function(id) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
//TODO Configuration for the host ?
url: this.env().baseURL.replace(/\/$/,"") + "/api/v1/bnf/"+id,
success: function(bnfDoc) {
var labels = bnfDoc.bnfids;
var expectedId = constants.BNF_ARK_BASE_ID + id;
resolve((expectedId in labels)?labels[expectedId]:null);
},
error: function(req, status, error) {
reject(status + ":" + error);
}
});
}.bind(this));
}
});