import Service from 'ember-service';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';

const RETRY_REQUEST_DELAY = 100;

export default Service.extend({
  api: injectService(),

  embeds: {},

  getEmbed(embedURL) {
    let embedPromise = this.embeds[embedURL];
    if (embedPromise) {
      return embedPromise;
    }
    embedPromise = new RSVP.Promise((resolve, reject) => {
      this._makeEmbedRequest(embedURL).then((embedInfo) => {
        resolve(embedInfo);
      }, (error) => {
        if (error.status === 500) {
          this.runTask(this._makeEmbedRequest(embedURL).then((embedInfo) => {
            resolve(embedInfo);
          }, (err) => {
            reject(err);
          }), RETRY_REQUEST_DELAY);
        } else {
          reject(error);
        }
      });
    });
    this.embeds[embedURL] = embedPromise;
    return embedPromise;
  },

  _makeEmbedRequest(embedURL) {
    return this.get('api').authRequest('get', `embed?url=${embedURL}`);
  }
});
