/* globals i18n */
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import Component from 'ember-component';
import { KEY_CODES } from 'web-client/utilities/keyboard';
import InteractivityDeferredComponent from 'web-client/mixins/interactivity-deferred-component';
import $ from 'jquery';
import run from 'ember-runloop';

const TWITTER_POST_DEFAULT_FLAG = "Twitch.feed.postToTwitterDefault";

export default Component.extend(InteractivityDeferredComponent, {
  classNameBindings: [':activity-create', 'textAreaFocus:activity-create--focus', 'showCreateActions::activity-create--oneline', ':pos-relative'],
  feeds: injectService(),
  notify: injectService(),
  embeds: injectService(),
  emotes: injectService('user-emotes'),

  messageText: '',
  postToTwitter: null,
  textAreaFocus: false,
  posting: false,
  embed: null,
  twitterConnected: computed.alias('feeds.meAsFeedUser.twitterConnected'),
  showEmoticonSelector: false,

  init() {
    this._super(...arguments);
    let feeds = this.get('feeds');
    let postTwitterDefault = feeds.getLocalStorageValue(TWITTER_POST_DEFAULT_FLAG);

    if (!postTwitterDefault) {
      feeds.setLocalStorageValue(TWITTER_POST_DEFAULT_FLAG, false);
      postTwitterDefault = false;
    }

    this.set('postToTwitter', postTwitterDefault);
    this.get('emotes').populate().then((rawEmoteSet) => {
      if (this.isDestroyed) { return; }
      this.set('rawEmoteSet', rawEmoteSet);
    });
  },

  didInsertElement() {
    this._super(...arguments);
    this.addEventListener(window, 'click', (e) => {
      let target = $(e.target);
      if (target.closest('.js-composer-emotes').length === 0) {
        this.set('showEmoticonSelector', false);
      }
    });
    this.reportInteractive();
  },

  focusIn() {
    this.set('textAreaFocus', true);
    this._resizeTextarea();
  },

  focusOut() {
    this.set('textAreaFocus', false);
    this._resizeTextarea();
  },

  keyUp() {
    this._resizeTextarea();
  },

  isDisabled: computed('posting', 'messageText', function() {
    let posting = this.get('posting');
    let messageText = this.get('messageText').trim();
    return posting || messageText.length === 0;
  }),

  keyDown(e) {
    let isDisabled = this.get('isDisabled');
    if (e.which === KEY_CODES.enter && !isDisabled) {
      if (this.get('nakedReturnToSubmit')) {
        this.send('createMessage');
        return false;
      } else if ((e.metaKey || e.ctrlKey)) {
        this.send('createMessage');
        return false;
      }
    }
    if (this.get('liveEmbed')) {
      this.debounceTask('_fetchEmbed', 150);
    }
  },

  _setTwitterPostDefault() {
    let feeds = this.get('feeds');
    feeds.setLocalStorageValue(TWITTER_POST_DEFAULT_FLAG, this.get('postToTwitter'));
  },

  _fetchEmbed() {
    let URLRegex = this.get('feeds.urlRegex');
    let messageURL = this.get('messageText').match(URLRegex);
    let currentEmbed = this.get('embed');
    if (messageURL) {
      if (!currentEmbed || !messageURL.contains(currentEmbed.request_url)) {
        this.get('embeds').getEmbed(messageURL[0]).then((embed) => {
          if (this.isDestroyed) { return; }
          if (!this.get('posting') && this.get('messageText') !== '') {
            this.set('embed', embed);
          }
        }, () => {
          this.set('embed', null);
        });
      }
    } else if (currentEmbed) {
      this.set('embed', null);
    }
  },

  _resizeTextarea() {
    let textArea = this.$('textarea')[0];
    if (!this.get('textAreaFocus') && !this.get('messageText').length) {
      textArea.style.height = null;
      return;
    }
    let height = textArea.style.height;
    // set the textareas height to 'auto' which will expand/shrink the textarea based on content
    textArea.style.height = 'auto';
    let scrollHeight = textArea.scrollHeight;
    // set the textarea to it's original height. Without this step, the textarea's CSS transition will not work
    textArea.style.height = height;
    if (scrollHeight !== height) {
      run.next(() => {
        if (textArea) {
          textArea.style.height = `${scrollHeight}px`;
        }
      });
    }
  },

  actions: {
    createMessage() {
      let body = this.get('messageText');
      let twitterShare = this.get('postToTwitter');
      let createMessageHandler = this.get('createMessage');
      let maxLength = this.get('maxLength');

      if (!this.get('feeds.meAsFeedUser')) {
        let isModal = this.get('isModal');
        if (!isModal && $.login instanceof Function) {
          $.login();
        }
        return;
      }
      if (body.length > maxLength) {
        this.get('notify').error(i18n(`It's over ${maxLength}!!!! Make your post shorter and try again.`));
        return;
      }

      this.set('posting', true);
      if (createMessageHandler instanceof Function) {
        createMessageHandler({body, twitterShare}).then(() => {
          if (this.isDestroyed) { return; }
          this.set('messageText', '');
          this.set('textAreaFocus', false);
          this.set('embed', null);
          this._setTwitterPostDefault();
          this._resizeTextarea();
        }, () => {
          if (this.isDestroyed) { return; }
          this.get('notify').error(i18n("There was a problem updating your feed. Please try again."));
        }).finally(() => {
          if (this.isDestroyed) { return; }
          this.set('posting', false);
        });
      } else {
        console.error('no createMessage handler was provided to the composer');
      }
    },

    insertEmote (emoteName) {
      let textarea = this.$('textarea')[0];
      let messageText = this.get('messageText');
      let selectionStart = textarea.selectionStart;
      let selectionEnd = textarea.selectionEnd;
      let front = messageText.substring(0, selectionStart);
      let back = messageText.substring(selectionEnd, messageText.length);

      if (front.length > 0 && front[front.length-1] !== ' ') {
        emoteName = ` ${emoteName}`;
      }

      this.set('messageText', `${front}${emoteName} ${back}`);
      textarea.value = `${front}${emoteName} ${back}`;
      this.set('showEmoticonSelector', false);
      $('.tipsy.tipsy-n').remove();
      textarea.focus();
      textarea.setSelectionRange(front.length + emoteName.length + 1, front.length + emoteName.length + 1);
    },

    toggleEmoteSelector() {
      this.toggleProperty('showEmoticonSelector');
    }
  }
});
