import Mixin from 'ember-metal/mixin';
import injectService from 'ember-service/inject';

/*
* Page Title Mixin for Routes
*
* Added to all routes by default in app/ext/routes.js
*
* Usage:
*  - If the route should inherit a title from its parents, do nothing.
*  - If the route should have its own title, define a buildPageTitle function
*    that returns an object containing a string `title` property.
*  - If the route should *not* have " - Twitch" appended to it, add a false
*    boolean `hasTwitchTitleSuffix` to the object returned by buildPageTitle.
*    By default, " - Twitch" is appended to all non-empty page titles.
*  - If the route dynamically inherits or sets its own title, set `title` to
*    a falsey value when it should inherit, and to a non-empty string otherwise.
*
* Example:
*  buildPageTitle() {
*    return {
*      title: 'A Cool Title',
*      hasTwitchTitleSuffix: false
*    };
*  }, // <title>A Cool Title</title>
*/
export default Mixin.create({
  headData: injectService(),

  actions: {
    updatePageTitle() {
      let titleObject = typeof this.buildPageTitle === 'function' ? this.buildPageTitle() : {};
      if (!titleObject.title) {
        return true;
      }

      let hasTwitchTitleSuffix = titleObject.hasTwitchTitleSuffix !== false; // undefined defaults to true
      this.get('headData').setTitle(titleObject.title, hasTwitchTitleSuffix);
    }
  }
});
