import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import { EMBED_TYPES } from 'web-client/utilities/embed-types';

export default Component.extend({
  embedService: injectService('embeds'),

  loadingEmbed: false,
  link: computed('embed.type', function () {
    let type = this.get('embed.type');
    return type === EMBED_TYPES.link || type === EMBED_TYPES.rich;
  }),
  embed: computed('embeds.[]', function () {
    return this.get('embeds.firstObject') || null;
  }),

  didReceiveAttrs() {
    let currentEmbed = this.get('embed');
    if (currentEmbed && !currentEmbed.type && currentEmbed.request_url) {
      this.set('loadingEmbed', true);
      this.get('embedService').getEmbed(currentEmbed.request_url).then((embed) => {
        if (this.isDestroyed) { return; }
        this.set('embed', embed);
      }).finally(() => {
        if (this.isDestroyed) { return; }
        this.set('loadingEmbed', false);
      });
    }
  }
});
