/* globals Twitch, i18n */

import Controller from 'ember-controller';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { htmlSafe } from 'ember-string';

const PREFIX_INVALID = i18n('Invalid entry. Please confine your expression to the characters a-z and 0-9.');
const PREFIX_LENGTH_REQUIREMENT = i18n('Your prefix must be between 3 to 10 characters');
const PREFIX_LOWERCASE_REQUIREMENT = i18n('Your prefix must begin with a lowercase letter.');

export default Controller.extend({
  api: injectService(),
  notify: injectService(),

  emoticonSet: computed.alias('model.emoticonSet'),
  emoticons: computed.alias('model.emoticons'),

  emoticonLimitReached: computed('emoticons.[]', 'emoticonSet.emoticon_limit', function() {
    return this.get('emoticons.length') >= this.get('emoticonSet.emoticon_limit');
  }),

  emoticonDeleteChecked: computed('emoticons.@each.checked', function () {
    let emoticons = this.get('emoticons');
    for (let i = 0; i < emoticons.length; i++) {
      if (emoticons[i].checked) {
        return true;
      }
    }
    return false;
  }),

  noEmoticonsChecked: computed.not('emoticonDeleteChecked'),

  maxLevelReached: computed('emoticonSet.emoticon_limit', 'emoticonSet.emoticon_limit_for_next_level', function () {
    return this.get('emoticonSet.emoticon_limit') === this.get('emoticonSet.emoticon_limit_for_next_level') ||
      !this.get('emoticonSet.emoticon_limit_for_next_level');
  }),

  emoticonsGainedOnLevelUp: computed('emoticonSet.emoticon_limit', 'emoticonSet.emoticon_limit_for_next_level', function () {
    return this.get('emoticonSet.emoticon_limit_for_next_level') -
      this.get('emoticonSet.emoticon_limit');
  }),

  subscriberCountStyle: computed('emoticonSet.subscribers_count', 'emoticonSet.subscribers_count_for_next_level', function () {
    let subscriberCount = this.get('emoticonSet.subscribers_count');
    let countToNextLevel = this.get('emoticonSet.subscribers_count_for_next_level');
    let percentComplete = (subscriberCount / countToNextLevel) * 100;

    return htmlSafe(`width: ${percentComplete}%`);
  }),

  emoticonEditMode: computed.bool('emoticon_edit_mode'),

  prefixPending: computed.equal('emoticonSet.prefix_state', 'pending'),

  prefixApproved: computed.equal('emoticonSet.prefix_state', 'active'),

  prefixRejected: computed.equal('emoticonSet.prefix_state', 'rejected'),

  prefix: null,

  actions: {
    updateNewPrefix(newValue) {
      this.set('newPrefix', newValue.toLowerCase());
    },

    enableEditingMode() {
      this.set('emoticon_edit_mode', true);
    },

    cancelEditingMode() {
      this.set('emoticon_edit_mode', false);
      let emoticons = this.get('emoticons');
      for (let i = 0; i < emoticons.length; i++) {
        this.set(`emoticons.${i}.checked`, false);
      }
    },

    submitEdit() {
      let emoticons = this.get('emoticons');
      let userLogin = Twitch.user.login();

      for (let i = emoticons.length - 1; i >= 0; i--) {
        let emoticonId = emoticons[i].id;
        let checked = emoticons[i].checked;

        if (checked) {
          this.get('api').request('del', `/api/ticket_products/${userLogin}/remove_emoticon`, { emoticon_id: emoticonId });
          emoticons.removeAt(i);
        }
      }

      this.set('emoticon_edit_mode', false);
    },

    savePrefix() {
      let prefix = this.get('newPrefix');
      let notify = this.get('notify');
      let model = this.get('model');

      if (!prefix) { return; }

      if (prefix.length < 3) {
        return notify.error(PREFIX_LENGTH_REQUIREMENT);
      }

      if (!prefix.match(/^[0-9a-z]+$/)) {
        return notify.error(PREFIX_INVALID);
      }

      if (!prefix[0].match(/^[a-z]+$/)) {
        return notify.error(PREFIX_LOWERCASE_REQUIREMENT);
      }

      model.set('prefix', prefix);
      model.save().catch((error) => {
        if (this.isDestroyed) { return; }

        if (error && error.responseJSON && error.responseJSON.message) {
          let message = error.responseJSON.message;

          if (error.status !== 200) {
            return notify.error(i18n(message));
          }

          return notify.success(i18n(message));
        }

        if (error && error.responseText) {
          return notify.error(error.responseText);
        }

        throw error;
      });
    }
  }
});
