import DefaultPinnedCheer from 'web-client/components/bits/pinned-cheers/default-pinned-cheer/component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import env from 'web-client/config/environment';
import { PINNED_CHEER_TYPES } from 'web-client/utilities/bits/constants-config';
import { SIZES } from 'web-client/components/progress-bar/countdown/component';

const CHAT_LINE_SELECTOR = '.pinned-cheers__message-wrapper > .chat-line';
const MESSAGE_SELECTOR = '.pinned-cheers__message-wrapper > .chat-line .message';
const MEASURE_MESSAGE_DELAY = env.delay.pinnedCheers.measure;
const UNEXPANDED_MAX_HEIGHT = 20;
const LINE_HEIGHT = 20;

export default DefaultPinnedCheer.extend({
  pinnedCheers: injectService('bits-pinned-cheers'),
  session: injectService(),
  chatSettings: injectService(),

  countdownDuration: null,
  countdownTotalDuration: null,
  countdownSize: SIZES.XS,

  isViewerModeratorOrHigher: false,

  classNames: ['pinned-cheers__message', 'js-bits-pinned-cheers-recent-cheer'],
  classNameBindings: ['expandMessage:expandMessage:'],

  userData: computed.readOnly('session.userData'),

  showDismissButton: computed('userData.id', 'isViewerModeratorOrHigher','chatSettings.showModIcons',  function() {
    let canDismiss = this.get('pinnedCheers').canDismissPinnedCheer(this.get('userData.id'), this.get('isViewerModeratorOrHigher'));
    let isMyPinnedCheer = String(this.get('userData.id')) === this.get('pinnedCheers.recentPinnedCheer.id');

    return isMyPinnedCheer || (canDismiss && this.get('chatSettings.showModIcons'));
  }),

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

    if (this.get('expandMessage')) {
      this._expandMessageContainer();
    }
  },

  actions: {
    toggleExpandMessage() {
      let isExpanded = this.toggleProperty('expandMessage');

      if (isExpanded) {
        this._expandMessageContainer();
      } else {
        this.$(CHAT_LINE_SELECTOR).css('max-height', UNEXPANDED_MAX_HEIGHT);
      }
    },

    measureMessage() {
      // this gets called from the didRender method inside of message-line. We need to wait on the children elements
      // to render in order to ensure that we're accurately measuring the message height.
      this.runTask(function () {
        let $messageBox = this.$(MESSAGE_SELECTOR);

        this.set('expandArrowVisible', $messageBox && $messageBox.height() > UNEXPANDED_MAX_HEIGHT);
      }, MEASURE_MESSAGE_DELAY);
    },

    dismissPinnedCheer() {
      this.get('pinnedCheers').dismissMessage(this.get('userData.id'), PINNED_CHEER_TYPES.RECENT);
    },

    expirePinnedCheer() {
      this.get('pinnedCheers').expireRecentMessage(this.get('cheerMessage'));
    }
  },

  _expandMessageContainer() {
    let $messageBox = this.$(MESSAGE_SELECTOR);
    let messageHeight = $messageBox.length ? $messageBox.height() : 0;

    // overshoot
    this.$(CHAT_LINE_SELECTOR).css('max-height', messageHeight + LINE_HEIGHT);
  }
});
