import Mixin from 'ember-metal/mixin';
import injectService from 'ember-service/inject';
import { trimQueryParams } from 'web-client/utilities/url-params';

const CANONICAL_BASE_URL = 'https://www.twitch.tv';

/*
* Canonical URL Mixin for Routes
*
* Added to all routes by default in app/ext/routes.js
*
* Usage:
*  - For routes that should have a default canonical URL (per the router), do nothing.
*  - For routes that should inherit its parents canonical URL, set hasOwnCanonicalUrl to false
*  - For routes that should have a custom canonical URL, override buildCanonicalPath
*/
export default Mixin.create({
  headData: injectService(),
  routingService: injectService('-routing'),
  hasOwnCanonicalUrl: true,
  _setCanonicalUrl(canonicalPath) {
    this.set('headData.canonicalUrl', CANONICAL_BASE_URL + canonicalPath);
  },

  /*
  * Override to build custom canonical paths
  */
  buildCanonicalPath() {
    /*
    * Note that this uses private services and APIs to generate the canonical URL
    * Empty objects and arrays are passed in to avoid affecting existing router state.
    */
    let canonicalPath = this.get('routingService').generateURL(this.routeName, [], {});

    /*
    * Unnecessary because query params are broken (see History reopening in app/router.js)
    * but trimming query params here as a pre-emptive measure.
    *
    * TODO: update CS:GO directory to use routes rather than query params,
    * or whitelist query params by overriding buildCanonicalPath
    */
    canonicalPath = trimQueryParams(canonicalPath);

    // Trim trailing slash if it exists
    if (canonicalPath.slice(-1) === '/') {
      canonicalPath = canonicalPath.slice(0, -1);
    }

    return canonicalPath;
  },

  actions: {
    updateCanonicalUrl() {
      if (this.get('hasOwnCanonicalUrl')) {
        this._setCanonicalUrl(this.buildCanonicalPath());
      } else {
        return true; // Bubble up
      }
    }
  }
});
