import Mixin from 'ember-metal/mixin';
import computed from 'ember-computed';

// Click handling for an onsite notification. Given a url, if the path is an ember
// route, transition to it, else open the url.
export default Mixin.create({
  router: computed(function() {
    return this.container.lookup('router:main');
  }),

  recognizer: computed('router', function() {
    return this.get('router').router.recognizer;
  }),

  // Returns whether the route can be transitioned to
  routeTo(url) {
    let result = this._parseUrl(url);
    let isTwitchRoot = result.hostname === "twitch.tv" || result.hostname === "www.twitch.tv";
    let canTransition = isTwitchRoot && this._isRecognized(result.pathname);
    if (canTransition) {
      this.get('router').transitionTo(result.pathname);
    } else {
      window.open(url);
    }

    return canTransition;
  },

  _isRecognized(path) {
    let result = this.get('recognizer').recognize(path);
    if (result.length) {
      let last = result[result.length - 1];
      return last.handler !== "404";
    }

    return false;
  },

  _parseUrl(url) {
    let parser = document.createElement('a');
    parser.href = url;
    return {
      pathname: parser.pathname,
      hostname: parser.hostname
    };
  }
});
