import Component from 'ember-component';
import computed from 'ember-computed';
import { htmlSafe } from 'ember-string';
import { keyboardListener } from 'web-client/utilities/keyboard';

const DEFAULT_SIZE = 'default';

const SIZES = {
  [DEFAULT_SIZE]: 'width: 420px;',
  bits: 'width: 540px',
  medium: 'width: 720px; height: 600px;',
  containerSm: 'max-width: 900px; min-width: 420px',
  containerMd: 'max-width: 1024px; min-width: 420px'
};

const SIZE_REGEX = /[0-9]+px/;
const WINDOW_CONTAINER_CLASS = 'twitch_subwindow_container';

export default Component.extend({
  classNameBindings: [
    'modalSize',
    `showModal:${WINDOW_CONTAINER_CLASS}`
  ],

  customHeight: '',
  customWidth: '',
  renderInPlace: false,
  onClose() {},
  onOpen() {},
  size: 'default',
  showModal: null, // Overriding provides full manual visibility control

  defaultShowModal: true,
  isVisible: computed('showModal', 'defaultShowModal', function () {
    let showModal = this.get('showModal');

    return showModal !== null ? showModal : this.get('defaultShowModal');
  }),

  subWindowStyles: computed('size', 'customWidth', 'customHeight', function() {
    let customHeight = this.get('customHeight');
    let customWidth = this.get('customWidth');
    let sanitizedHeight = this._sanitizeSizeProperty(customHeight);
    let sanitizedWidth = this._sanitizeSizeProperty(customWidth);
    if (sanitizedHeight !== '' && sanitizedWidth !== '') {
      return htmlSafe(`width: ${sanitizedWidth}; height: ${sanitizedHeight};`);
    }

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

  modalSizeClassName: computed('size', function() {
    return `${this.get('size')}-modal`;
  }),

  didInsertElement() {
    this._super(...arguments);
    this.get('onOpen')();

   this.addEventListener(...keyboardListener({
      esc: this._closeModal
    }));
  },

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

    if (this.get('showModal')) {
      this._closeModal();
    }
  },

  _closeModal() {
    this.set('defaultShowModal', false);
    this.get('onClose')();
  },

  _sanitizeSizeProperty(value) {
    if (value === '') {
      return '';
    }

    let matches = value.match(SIZE_REGEX);
    if (matches) {
      return matches[0];
    }
    return '';
  },

  actions: {
    closeModal() {
      this._closeModal();
    },
    containerClick(event) {
      if (this.$(event.target).hasClass(WINDOW_CONTAINER_CLASS)) {
        this._closeModal();
      }
    }
  }
});
