import Component from 'ember-component';
import Evented from 'ember-evented';
import computed from 'ember-computed';
import run from 'ember-runloop';
import $ from 'jquery';
import { htmlSafe } from 'ember-string';

const ESC_KEYCODE = 27;
const SIZES = {
  default: 'width: 420px;',
  bits: 'width: 540px',
  medium: 'width: 720px; height: 600px;',
  containerMd: 'max-width: 1024px;'
};

const sizeRegExp = /[0-9]+px/;

export default Component.extend(Evented, {
  classNames: ['twitch_subwindow_container'],

  // can be 'default' or 'medium'
  size: 'default',
  useCustomSize: false,
  customWidth: '',
  customHeight: '',

  sizeStyles: computed('size', 'useCustomSize', 'customWidth', 'customHeight', function () {
    let customHeight = this._sanitizeSizeProperty(this.get('customHeight'));
    let customWidth = this._sanitizeSizeProperty(this.get('customWidth'));

    if (this.get('useCustomSize') && customHeight !== '' && customWidth !== '') {
      return htmlSafe(`width: ${customWidth}; height: ${customHeight};`);
    }

    return htmlSafe(SIZES[this.get('size') || 'default']);
  }),

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

    console.warn(`${this} is deprecated, please use app/components/common/modal-dialog going forward`);
  },

  didInsertElement() {
    this._super(...arguments);
    this._closeOnExteriorClick();
    this._closeOnEsc();
    this.sendAction('didOpen');
  },

  willDestroyElement() {
    this._super(...arguments);
    let elementId = this.get('elementId');
    $(document).off(`keyup.${elementId}`);
    $('body').off(`click.${elementId}`);
    this.sendAction('didClose');
  },

  _closeOnEsc() {
    let elementId = this.get('elementId');
    $(document).on(`keyup.${elementId}`, e => {
      if (e.keyCode === ESC_KEYCODE) {
        run(this, 'send', 'closeModal');
      }
    });
  },

  _closeOnExteriorClick() {
    let elementId = this.get('elementId');
    $('body').on(`click.${elementId}`, e => {
      if ($(e.target).hasClass('twitch_subwindow_container')) {
        run(this, 'send', 'closeModal');
      }
    });
  },

  _sanitizeSizeProperty(value) {
    let matches = value.match(sizeRegExp);

    if (matches) {
      return matches[0];
    }
    return '';
  },

  actions: {
    closeModal() {
      this.sendAction();
    }
  }
});
