import injectService from 'ember-service/inject';
import Component from 'ember-component';
import computed from 'ember-computed';

const NEWSFEED_ONBOARDING_FLAG = 'Twitch.feed.userClosedBetaOnboarding';

export default Component.extend({
  feeds: injectService(),
  trackingInfo: { feed_type: 'news' },
  browse: injectService(),

  isBrowseExperimentEnabled: computed.readOnly('browse.isBrowseExperimentEnabled'),

  loading: true,
  loadingMore: false,
  feed: null,
  truncatePostAfter: null,
  numPostPreviewLines: null,
  showOnboardingExperience: computed(function () {
    return !this.get('feeds').getLocalStorageValue(NEWSFEED_ONBOARDING_FLAG);
  }),

  posts: computed.readOnly('feed.posts'),

  init() {
    this._super();

    let feedsService = this.get('feeds');
    this.set('loading', true);
    feedsService.getNewsfeed().then(
      (feed) => {
        if (this.isDestroyed) { return; }
        this.set('feed', feed);
      },
      (err) => {
        if (this.isDestroyed) { return; }
        this.set('error', err);
      }).finally(() => {
        if (this.isDestroyed) { return; }
        this.set('loading', false);
      }
    );
  },

  actions: {
    loadMore() {
      let feeds = this.get('feeds');
      let feed = this.get('feed');

      this.set('loadingMore', true);
      feeds.loadMoreForRecentFeed(feed).finally(() => {
        if (this.isDestroyed) { return; }
        this.set('loadingMore', false);
      });
    },

    deletePost(post) {
      return this.get('feeds').deleteMessage(post).then(() => {
        let feed = this.get('feed');
        feed.get('posts').removeObject(post);
      });
    },

    closeCommentsOnboarding() {
      let feeds = this.get('feeds');
      feeds.setLocalStorageValue(NEWSFEED_ONBOARDING_FLAG, true);
      this.set('showOnboardingExperience', false);
    },

    createPost(params) {
      let feeds = this.get('feeds');
      return feeds.createPost(params).then((post) => {
        if (this.isDestroyed) { return; }
        let trackingProps = {
          status_update_id: post.get('id'),
          post_to_twitter: params.twitterShare,
          content: post.get('body'),
          channel: post.get('user.login'),
          has_url: feeds.urlRegex.test(post.get('body')),
          connected_to_twitter: feeds.get('meAsFeedUser.twitterConnected'),
          user_id: post.get('user.id'),
          embed_type: post.get('embeds.firstObject.type') || null,
          embed_provider: post.get('embeds.firstObject.provider_name') || null
        };
        feeds.trackEvent('feed_update', this.get('trackingInfo'), trackingProps);
      });
    }
  }
});
