/* globals Twitch, URI */

import Component from 'ember-component';

import Ember from 'ember';
import cdnUrl from 'web-client/utilities/cdn-url';
import computed from 'ember-computed';
import $ from 'jquery';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';

const { observer } = Ember;
const TWITCH_DOMAIN = 'twitch.tv';
const EXTENSIONS_ID_REGEX = /^ext\-(.+)/;

export default Component.extend({
  store: injectService(),
  tagName: "li",
  classNames: ['panel'],
  layoutName: "components/panels/show",
  showConfirmDelete: false,
  attributeBindings: "data-id",
  "data-id": computed.alias('content.id'),
  selectKind: computed.equal('content.kind', null),
  isDefault: computed.equal('content.kind', 'default'),
  isTeespring: computed.equal('content.kind', 'teespring'),

  // zacksim: To avoid modifying the database to store the
  // panel extensions id, the "kind" field is being overloaded to hold
  // the extension and its id in a string. eg: "ext-1234"
  isExtensionKind: computed.match('content.kind', EXTENSIONS_ID_REGEX),
  isExtension: computed('isExtensionKind', 'extension', function() {
    return this.get('isExtensionKind') && this.get('extension') !== null;
  }),
  extension: computed('content.kind', 'installedExtensions', function() {
    let idMatch = this.get('content.kind').match(EXTENSIONS_ID_REGEX);
    let panelExtensionId = idMatch && idMatch.length > 1 ? idMatch[1] : '';
    if (panelExtensionId) {
      let installedExtensions = this.get('installedExtensions');
      if (!installedExtensions) {
        return null;
      }
      let foundExtension = installedExtensions.find(
        extension => {
          return extension.get('extension.id') === panelExtensionId;
        }
      );
      // Find returns undefined on error, convert to null
      return foundExtension ? foundExtension : null;
    }
    return null;
  }),
  isAnyExtensionInstalled: computed.notEmpty('installedExtensions'),

  api: injectService(),
  tracking: injectService(),

  didRender: function () {
    this._super(...arguments);

    // We do this jquery binding here becuase we want to attach to all links
    // even ones that are provided in the parsed markdown from users.
    let $contentATags = this.$('.js-panel-content a');
    if (this._linkClickHandler) {
      $contentATags.off('click', this._linkClickHandler);
    }
    this._linkClickHandler = (e) => {
      run(() => {
        this.handleLinkClick(e);
      });
    };

    for (let i = 0; i < $contentATags.length; i++){
      let $aTag = $($contentATags[i]);
      let currentUri = URI($aTag.attr('href'));
      let rel = 'noopener noreferrer';

      if (currentUri.domain() !== TWITCH_DOMAIN) {
        rel += ' nofollow';
      }

      $aTag.on('click', this._linkClickHandler);
      $aTag.attr('target', '_blank');
      $aTag.attr('rel', rel);
    }
  },

  willDestroyElement: function () {
    this._super(...arguments);
    this.$('.js-panel-content a').off('click', this._linkClickHandler);
  },

  handleLinkClick: function (e) {
    let linkHandler = this.get('onLinkClick');
    if (linkHandler && linkHandler instanceof Function) {
      linkHandler({
        target_link_url: e.target.href,
        target_link_text: e.target.innerText,
        panel_title: this.get('content.data.title'),
        panel_index: this.get('content.display_order')
      });
    }
  },

  input: function () {
    this.set('isDirty', true);
  },

  submitDisabled: computed.not('isDirty'),

  imageUploadHref: computed('content.channel', function () {
    return `${Twitch.api.config.baseUrl}/api/channels/${this.get('content.channel')}/panels/upload`;
  }),

  spinnerImage: computed(function () {
    return cdnUrl('images/spinner.gif');
  }),

  safeHref: computed('content.data.link', function () {
    // Todo: sanitize this input before save in rails instead of like this.
    // source: http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the
    /* eslint-disable max-len */
    const URL_REGEX = /^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)$/;
    /* eslint-enable max-len */
    let href = this.get('content.data.link') || '';
    if (URL_REGEX.test(href)) {
      return href;
    }
  }),

  _rollbackOnExitEditMode: observer('editMode', function () {
    if (!this.get('editMode')) {
      if (this.get("content._id")) {
        // Rollback existing panels
        this.get("content").rollback();
        this.set("isDirty", false);
      } else {
        // Delete new panels
        this.sendAction('destroyPanel', this);
      }
    }
  }),

  savePanel: function () {
    if (!this.get('isDirty')) { return; }

    if (this.get('content.kind') === 'teespring') {
      this.get('tracking').trackEvent({
        event: 'teespring_panel_added',
        data: {}
      });
    }
    if (!this.get('content._id')) { // Create new panel
      this.set('isSaving', true);
      this.get('api').request('post', `/api/channels/${this.get("content.channel")}/panels`, {
        data: this.get('content.data'),
        kind: this.get("content.kind")
      }).then((data) => {
        if (this.isDestroyed) { return; }
        this.set('isSaving', false);
        data.id = data._id; // Copied from PanelModel.deserialize
        this.get("content").setProperties(data);
      });
    } else { // Update existing panel
      this.get("content").save({
        id: this.get('content._id'),
        channel: this.get('content.channel'),
        data: this.get('content.data')
      });
    }
    this.set('isDirty', false);
  },

  actions: {
    setKind: function (kind) {
      this.set("content.kind", kind);
      if (kind === "teespring") {
        this.set('isDirty', true);
      }
    },

    imageUploaded: function () {
      this.set('isDirty', true);
    },

    toggleDeleteOverlay: function () {
      this.set('showConfirmDelete', !this.get('showConfirmDelete'));
    },

    savePanel: function () {
      this.savePanel();
    },

    destroyPanel: function (panel) {
      this.sendAction('destroyPanel', panel);
    },

    trackPanelClick() {
      this.get('tracking').trackEvent({
        event: 'panel_shirt_click',
        data: {}
      });

      window.open(`${this.get('content.data.campaign_url')}?utm_source=twitch_panel`);
    },

    extensionsSelect(extId) {
      this.set('content.kind',`ext-${extId}`);
      this.set('isDirty', true);
      this.savePanel();
    },

    extensionsLiveSettings() {
      alert('TODO: This will open live settings');
    },

    extensionsConfig() {
      alert('TODO: This will open config');
    }
  }
});
