/* globals Twitch */
import RSVP from 'rsvp';
import injectService from 'ember-service/inject';
import Component from 'ember-component';
import computed from 'ember-computed';
import { A as emberA } from 'ember-array/utils';

const COMMENTS_ONBOARDING_FLAG = 'Twitch.feed.userClosedCommentsOnboarding';

export default Component.extend({
  classNames: ['activity-container'],
  feeds: injectService(),
  trackingInfo: { feed_type: 'channel' },
  loading: false,
  loadingMore: false,
  feed: null,
  showComposer: null,
  showOnboardingExperience: computed('user', function () {
    let user = this.get('user');
    let isChannelOwner = user === Twitch.user.login();
    return !this.get('feeds').getLocalStorageValue(COMMENTS_ONBOARDING_FLAG) && isChannelOwner;
  }),

  _loadedUser: null,
  _firstFeedRender: true,

  didReceiveAttrs() {
    let oldUser = this.get('_loadedUser');
    let newUser = this.get('user');

    if (oldUser === null || oldUser !== newUser) {
      this.loadFeed(newUser);
      this.set('_loadedUser', newUser);
    }
  },

  willDestroyElement() {
    this._super(...arguments);

    let feed = this.get('feed');
    let feedsService = this.get('feeds');
    if (feed) {
      feedsService.unbindLiveFeed(feed);
    }
  },

  loadFeed(user) {
    this.set('loading', true);
    this.set('_firstFeedRender', true);

    return new RSVP.Promise((resolve, reject) => {
      if (!user) {
        // This is where the default post is set
        this.set('feed', null);
        return reject("Cannot load feed for undefined user");
      }
      resolve(this.get('feeds').getFeedForUser(user));
    }).finally(() => {
      if (this.isDestroyed) { return; }
      this.set('loading', false);
      let currentFeed = this.get('feed');
      if (currentFeed) {
        this.get('feeds').unbindLiveFeed(currentFeed);
      }
    }).then((result) => {
      if (this.isDestroyed) { return; }
      this.get('feeds').bindLiveFeed(result);
      this.set('feed', result);
    }, (error) => {
      if (!this.isDestroyed) {
        this.set('feed', null);
      }
      // TODO: Handle retrying if it was a server side error (>=500)
      throw error;
    });
  },

  posts: computed('feed.posts.[]', function () {
    let feed = this.get('feed');
    if (feed) {
      let maxPostsToDisplay = this.get('maxPostsToDisplay');
      let posts = feed.get('posts');
      if (maxPostsToDisplay) {
        return posts.slice(0, maxPostsToDisplay);
      }
      return posts;
    }
    return emberA([]);
  }),

  isEmptyFeed: computed.empty('posts'),

  actions: {
    loadMore() {
      let feeds = this.get('feeds');
      let user = this.get('user');
      let feed = this.get('feed');
      this.set('loadingMore', true);
      feeds.loadMoreForChannelFeed(user, feed).then(() => {
        if (this.isDestroyed) { return; }
        this.set('loadingMore', false);
      });
    },

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

    closeCommentsOnboarding() {
      let feeds = this.get('feeds');
      feeds.setLocalStorageValue(COMMENTS_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);
      });
    }
  }
});
