import Component from 'ember-component';
import injectService from 'ember-service/inject';
import ClickOutsideMixin from 'web-client/mixins/click-outside';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';
import { JTV_USER_PICTURES_404_USER_70X70_URL } from 'web-client/utilities/urls/static-cdn';
import { CREATIVE } from 'web-client/utilities/game-names';
import run from 'ember-runloop';
import { uploadLegacyData } from 'web-client/utilities/upload-form-data';

const ERROR_FILE_TOO_LARGE = 'File too large.';
const ERROR_FILE_WRONG_TYPE = 'Incompatible format. File must be an image.';
const ERROR_FILE_OTHER = 'Upload error';
const FILE_ACCEPTED_TYPES = '^image/';
const FILE_MAX_SIZE = 3000000;
const PROFILE_LOGO_ANIMATION_INTERVAL = 50;

export default Component.extend(ClickOutsideMixin, {
  session: injectService(),
  feeds: injectService(),
  tracking: injectService(),
  ajax: injectService(),
  clips: injectService(),
  collections: injectService(),
  channel: null,
  vod: null,
  canEditBanner: null,
  previewImage: null,
  uploadImageTemplate: 'shared/upload-image',
  areTabsCollapsed: computed.or('isVideosTabCollapsed', 'isFollowersTabCollapsed', 'isFollowingTabCollapsed'),
  isVideosTabCollapsed: true,
  isClipsTabCollapsed: true,
  isFollowersTabCollapsed: true,
  isFollowingTabCollapsed: true,
  isShowingCollapsedNav: false,
  isShowingFollowNotificationControls: false,
  shouldOverflow: computed.or('isShowingCollapsedNav', 'isShowingFollowNotificationControls'),

  showCommissionButton: computed('channel.game', 'channel.creative.commission_button', function() {
   return this.get('channel.game') === CREATIVE && !!this.get('channel.creative.commission_button');
  }),

  shouldShowIndexBarCss: computed('isSubNavExperiment', 'isSmallBar', 'isChannelIndex', function() {
    return this.get('isSubNavExperiment') && this.get('isSmallBar') && this.get('isChannelIndex');
  }),

  shouldShowSmallBarCss: computed('isSubNavExperiment', 'isSmallBar', function() {
    return this.get('isSubNavExperiment') && this.get('isSmallBar');
  }),

  shouldShowFixedBarCss: computed('isSubNavExperiment', 'isSmallBar', 'isFixed', function() {
    return (this.get('isSubNavExperiment') && !this.get('isSmallBar')) || (!this.get('isSubNavExperiment') && this.get('isFixed'));
  }),

  clickedOutside() {
    this.$('#collapsedNav').hide();
    this.set('isShowingCollapsedNav', false);
  },

  init() {
    this._super(...arguments);
    this.get('channel.videos').load();
  },

  didReceiveAttrs() {
    this._super(...arguments);
    assert('top-bar component requires channel argument', !!this.get('channel.id'));

    run.later(this, 'checkTabCollapse', PROFILE_LOGO_ANIMATION_INTERVAL);
  },

  videosCount: computed.readOnly('channel.videos.total'),

  _checkFile(file) {
    if (!file.type.match(FILE_ACCEPTED_TYPES)) {
      this.set('errorMessage', ERROR_FILE_WRONG_TYPE);
      this.set('isLoading', false);
      return false;
    }
    if (file.size > FILE_MAX_SIZE) {
      this.set('errorMessage', ERROR_FILE_TOO_LARGE);
      this.set('isLoading', false);
      return false;
    }
    return true;
  },

  checkTabCollapse() {
    let wereTabsCollapsed = this.get('areTabsCollapsed');

    if (!this.$('.js-cn-bar') || !this.$('.cn-tabs--2') || !this.$('js-collapsed-nav-wrapper') || !this.$('.js-cn-tab-live') ||
      !this.$('.js-cn-tab-videos') || !this.$('.js-cn-tab-followers') || !this.$('.js-cn-tab-following')) {
        return;
    }

    // Space of the container containing the Follow / Subscribe buttons
    this.buttonsContainerWidth = this.$('.cn-tabs--2').width();

    // Space of top nav
    this.topBarWidth = this.$('.js-cn-bar').width();
    this.collapsedNavBtn = this.$('.js-collapsed-nav-wrapper').width();

    this.liveTabWidth = this.$('.js-cn-tab-live').width();

    if (!this.get('areTabsCollapsed')) {
      this.videosTabWidth = this.$('.js-cn-tab-videos').width();
      this.followersTabWidth = this.$('.js-cn-tab-followers').width();
      this.followingTabWidth = this.$('.js-cn-tab-following').width();
      this.clipsTabWidth = this.$('.js-cn-tab-clips').width();
      this.collectionsTabWidth = this.$('.js-cn-tab-playlists').width();
    }

    let spaceUsed = this.buttonsContainerWidth + this.liveTabWidth + this.videosTabWidth +
                    this.followersTabWidth + this.followingTabWidth + this.collapsedNavBtn + 6;

    let isClipsTabEnabled = this.get('clips.isClipsTabEnabled');
    let isCollectionsTabEnabled = this.get('collections.isEnabled');

    if (isClipsTabEnabled) {
      spaceUsed += this.clipsTabWidth;
    }

    if (isCollectionsTabEnabled) {
      spaceUsed += this.collectionsTabWidth;
    }

    // Check if there is space for the Following Tab
    if (spaceUsed >= this.topBarWidth) {
      this.set('isFollowingTabCollapsed', true);
      spaceUsed -= this.followingTabWidth;
    } else {
      this.set('isFollowingTabCollapsed', false);
    }

    // Check if there is space for the Followers Tab
    if (spaceUsed >= this.topBarWidth) {
      this.set('isFollowersTabCollapsed', true);
      spaceUsed -= this.followersTabWidth;
    } else {
      this.set('isFollowersTabCollapsed', false);
    }

    if (isClipsTabEnabled) {
      if (spaceUsed >= this.topBarWidth) {
        this.set('isClipsTabCollapsed', true);
        spaceUsed -= this.clipsTabWidth;
      } else {
        this.set('isClipsTabCollapsed', false);
      }
    }

    if (isCollectionsTabEnabled) {
      if (spaceUsed >= this.topBarWidth) {
        this.set('isCollectionsTabCollapsed', true);
        spaceUsed -= this.clipsTabWidth;
      } else {
        this.set('isCollectionsTabCollapsed', false);
      }
    }

    // Check if there is space for the Videos Tab
    if (spaceUsed >= this.topBarWidth) {
      this.set('isVideosTabCollapsed', true);
      spaceUsed -= this.videosTabWidth;
    } else {
      this.set('isVideosTabCollapsed', false);
    }

    if (wereTabsCollapsed !== this.get('areTabsCollapsed')) {
      // Rerun the calculations to account for the insertion / removal of the collapsed nav button
      run.scheduleOnce('afterRender', this, 'checkTabCollapse');
    }
  },

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

    this.get('clips').checkClipsTabExperiment();
    this.checkTabCollapse();
    this.addEventListener(window, 'resize', this.checkTabCollapse.bind(this));
  },

  actions: {
    clickTab(route) {
      this.$('#collapsedNav').hide();
      this.set('isShowingCollapsedNav', false);
      this.sendAction('scrollForUser', route);
    },

    toggleCollapsedNav() {
      this.get('clips').dismissUpsell();
      this.$('#collapsedNav').toggle();
      this.toggleProperty('isShowingCollapsedNav');
    },

    enableEditing() {
      this.set('isEditing', true);
    },

    onFileDrop(file) {
      this.set('isLoading', true);
      this.set('errorMessage', '');

      if (this._checkFile(file)) {
        return uploadLegacyData('/settings', {'user[profile_image]': file}).then(() => {
          return this.get('channel').reload();
        }).then(() => {
          this.get('closeModal')();
        }).catch(xhr => {
          if (xhr.target && xhr.target.status & xhr.target.status === 413) {
            this.set('errorMessage', ERROR_FILE_TOO_LARGE);
          } else {
            this.set('errorMessage', ERROR_FILE_OTHER);
          }
        }).finally(() => {
          this.set('isLoading', false);
        });
      }
    },

    removeAvatar() {
      this.set('channel.logo', JTV_USER_PICTURES_404_USER_70X70_URL);

      return uploadLegacyData('/settings', {'user[delete_profile_image]': true}).then(() => {
        this.get('channel').reload();
      }).catch(() => {
        this.get('channel').rollbackAttributes();
      });
    },

    toggleShowBalloon() {
      this.toggleProperty('showBalloon');
    },

    dismissClipsNavHotspot() {
      this.get('clips').dismissUpsell();
    }
  }
});
