/* globals Twitch, i18n */
import Controller from 'ember-controller';
import PlayerViewControllerMixin from 'web-client/mixins/player-view-controller';
import utils from 'web-client/utilities/main';
import computed, { and } from 'ember-computed';
import { CREATIVE } from 'web-client/utilities/game-names';
import { assign as merge } from 'ember-platform';
import observer from 'ember-metal/observer';
import injectController from 'ember-controller/inject';
import injectService from 'ember-service/inject';

let ChannelController = Controller.extend(PlayerViewControllerMixin, {
  playerWasPaused: false,
  channelModel: null, // Set by the router with the Ember Data Channel Model

  globals: injectService(),
  tracking: injectService(),
  presence: injectService('twitch-presence/presence'),
  isInMaintenanceMode: computed.alias('globals.isInMaintenanceMode'),
  mobaWhitelist: computed.alias('globals.mobaWhitelist'),
  channelVideosTab: injectService(),
  showVideosTab: computed.alias('channelVideosTab.isEnabled'),

  userModel: computed('content.id', function() {
    let id = this.get('content.id');
    if (id) {
      return this.get('store').findRecord('user', id);
    }
  }),

  application: injectController(),
  session: injectService(),
  layout: injectService(),
  settings: injectService('chatSettings'),
  chat: injectController(),
  feeds: injectService(),

  feedsLoadingMore: false,
  shareText: i18n("Share"),

  _redirectChannel: observer('content.redirectChannel', function () {
    if (this.get('content.redirectChannel')) {
      window.location = Twitch.uri.channel(this.get('content.redirectChannel'));
    }
  }),

  isPostOverlayOpen: computed('application.currentRouteName', function () {
    let currentRoute = this.get('application.currentRouteName');
    return currentRoute === 'channel.index.post';
  }),

  relatedChannels: computed('content.relatedChannels', 'content.isLoading', function () {
    if (this.get('content.relatedChannels') && !this.get('content.relatedChannels.isLoaded')) {
      this.get('content.relatedChannels').load();
    }
    return this.get('content.relatedChannels');
  }),

  highlights: computed('content.highlights', function () {
    if (this.get('content.highlights') && !this.get('content.highlights.isLoaded')) {
      this.get('content.highlights').load();
    }
    return this.get('content.highlights');
  }),

  pastBroadcasts: computed('content.pastBroadcasts', function () {
    if (this.get('content.pastBroadcasts') && !this.get('content.pastBroadcasts.isLoaded')) {
      this.get('content.pastBroadcasts').load();
    }
    return this.get('content.pastBroadcasts');
  }),

  videos: computed('content.videos', function () {
    if (this.get('content.videos') && !this.get('content.videos.isLoaded')) {
      this.get('content.videos').load();
    }
    return this.get('content.videos');
  }),

  isLiveAccordingToKraken: computed('content.stream', 'content.stream.isLoaded', function () {
    if (!this.get('content.stream.isLoaded')) {
      return false;
    }
    return !this.get('content.stream.isOffline');
  }),

  isLive: computed('isLiveAccordingToKraken', 'model.playerIsLive', function () {
    let isLiveKraken   = this.get('isLiveAccordingToKraken'),
        isLivePlayer   = this.get('model.playerIsLive');

    if (isLivePlayer !== undefined) {
      return isLivePlayer;
    }
    return isLiveKraken;
  }),

  updatePresence(calledFromRouter) {
    if (this.isDestroyed || !Twitch.user.isLoggedIn()) { return; }

    let hostedChannel = this.get('content.hostModeTarget');

    if (calledFromRouter || (!this.get('isLive') && !hostedChannel) || this.get('isPlaylist')) {
      return this.get('presence').updateLatestActivity();
    }

    let presence = {
      type: 'watching',
      game: this.get('content.game') || ' ',
      channel_display_name: this.get('content.display_name'),
      channel_login: this.get('content.id'),
      channel_id: this.get('model._id').toString()
    };

    if (hostedChannel) {
      presence.game = hostedChannel.get('game');
      presence.hosted_channel_display_name = hostedChannel.get('displayName');
      presence.hosted_channel_login = hostedChannel.get('name');
      presence.hosted_channel_id = hostedChannel.get('_id').toString();
    }

    this.get('presence').updateLatestActivity(presence);
  },

  isPlaylist: computed('content.stream.isPlaylist', 'model.playerIsPlaylist', function () {
    let isPlaylistAccordingToKraken = this.get('content.stream.isPlaylist'),
        isPlaylistPlayer = this.get('model.playerIsPlaylist');

    return isPlaylistPlayer !== undefined ? isPlaylistPlayer : isPlaylistAccordingToKraken;
  }),

  isEditable: computed('content.id', function () {
    let { isAuthenticated, userData } = this.get('session');
    return isAuthenticated && (
      userData.login === this.get('content.id') || // owns this channel
      userData.is_admin ||
      userData.is_staff
    );
  }),

  isChannelOwner: computed('content.id', function () {
    return this.get('session.userData.login') === this.get('content.id');
  }),

  canGenerateClips: and('isLive', 'session.isAuthenticated'),

  toggleChat: function () {
    Twitch.chat.toggle();
  },

  hasBio: computed('user.bio', function () {
    return this.get('user.bio.length') > 0;
  }),

  channelHref: computed('content.id', function () {
    return Twitch.uri.channel(this.get('content.id'));
  }),

  channelUrl: computed('content.id', function () {
    return Twitch.canonicalUrl.channel(this.get('content.id'));
  }),

  loadUserData: function () {
    if (!this.get('content.user.isLoaded')) {
      this.get('content.user').load();
    }
  },

  playerData: computed('content.id', function () {
    return `/widgets/live_embed_player.swf?channel=${this.get('content.id')}`;
  }),

  playlistHelperText: computed('content.display_name', function () {
    let translatedMessage = i18n("{{display_name}} is sharing a playlist of recorded videos. The channel is not live when you see this label.");
    return translatedMessage.replace('{{display_name}}', this.get('content.display_name'));
  }),

  trackingProps: computed('content.id', 'content.game', function() {
    return {
      channel: this.get('content.id'),
      game: this.get('content.game')
    };
  }),

  isTheatreMode: computed.readOnly('layout.isTheatreMode'),
  isCreative: computed.equal('content.game', CREATIVE),

  actions: {
    loadMoreVideos() {
      let videos = this.get('content.videos');

      if (videos) {
        videos.loadMore();
      }
    },

    openPost(post) {
      this.transitionToRoute('channel.index.post', post);
    },

    panelLinkClick(context) {
      this.get('tracking').trackEvent({
        event: 'panel_link_click',
        data: merge(context, {
          channel: this.get('content.id'),
          channel_live: this.get('isLive'),
          login: this.get('session.userData.login')
        })
      });
    }
  }
});

utils.setOnReady(ChannelController, {
  propertyName: 'isLivePromise',

  readyToResolveCondition: computed('content.stream', 'content.stream.isLoading', function () {
    let streamObj             = this.get('content.stream'),
        streamObjExists       = !!streamObj,
        streamHasBeginLoading = this.get('content.stream.isLoading') !== undefined,
        streamHasLoaded       = this.get('content.stream.isLoading') === false;

    if (streamObjExists && !streamHasBeginLoading) {
      streamObj.load();
    }
    return streamHasLoaded;
  }),

  value: function () {
    return !!this.get('content.stream.isLoaded');
  }
});

export default ChannelController;
