/* globals URI SiteOptions */

import EmberRouter from 'ember-router';
import HistoryLocation from 'ember-locations/history';
import get from 'ember-metal/get';
import config from 'web-client/config/environment';
import TrackingRouterMixin from 'web-client/mixins/tracking-router';
import ResetResumeWatchingMixin from 'web-client/mixins/reset-resume-watching';
import { getIEVersion } from 'web-client/utilities/user-agent';
import on from 'ember-evented/on';
import { trimQueryParams } from 'web-client/utilities/url-params';

// IE9 and below do not support pushState. When they try to visit the profile page
// they will end up on the directory because instead of expecting the
// URL to be /:channel/profile they expect it to be /:channel#profile.
// For now we are adding hashes manually for IE. URLs in IE will be ugly but so be it.
// Once we migrate Twitch front page to ember, we can properly adjust our routes
// to avoid hacking this. IE 10 will also fix this problem.

const ieVersion = getIEVersion();
const useHashLocation = !!(ieVersion && ieVersion < 10);

if (useHashLocation) {
  window.location.hash = URI().path();
} else if (window.location.hash.length > 0) {
  window.location.hash = '';
}

// Sets location type to none for testing.
// This only exists here because we already manually manage
// locationType here.

let locationType;

if (config.environment === 'test') {
  locationType = 'none';
} else if (SiteOptions.embedEmberComponents) {
  locationType = 'embed-components';
} else if (useHashLocation) {
  locationType = 'hash';
} else {
  locationType = 'history';
}

HistoryLocation.reopen({
  getURL() {
    let rootURL = get(this, 'rootURL').replace(/\/$/, '');
    let url = get(this, 'location').pathname;
    let search = get(this, 'location').search;

    url = url.replace(rootURL, '');

    return url + search;
  }
});

let Router = EmberRouter.extend(TrackingRouterMixin, ResetResumeWatchingMixin, {
  updateCanonicalUrl: on('didTransition', function () {
    this.send('updateCanonicalUrl');
  }),

  updatePageTitle: on('didTransition', function () {
    this.send('updatePageTitle');
  }),

  location: locationType,

  handleURL(url) {
    url = trimQueryParams(url); // TODO: this may be clobbering Ember's awareness of query params on non-transitions

    return this._super.apply(this, [url]);
  }
});

Router.map(function () {
  this.route('index', { path: '/' });
  this.route('directory', function () {
    this.route('games', { path: '/' });
    this.route('communities', { path: '/communities' });
    this.route('discover');

    /** This route is only used for CS:GO right now, but will eventually consume all game lists
        when we generalize the ability to filter by metadata. */
    function csgo() {
      this.route('channels',  {path: '/'}, function () {
        this.route('filtered',  {path: 'map/:map'});
      });
      this.route('videos', function () {
        this.route('video-type', {path: '/:videoType'});
      });
      this.route('clips');
    }

    this.route('csgo', {path: 'game/Counter-Strike: Global Offensive'}, csgo);

    this.route('creative', { path: 'game/Creative' }, function () {
      this.route('browse');
      this.route('hashtag', { path: ':tag/' }, function () {
        this.route('videos');
        this.route('top');
      });
      this.route('communities', function() {});
    });

    this.route('game-details', { path: 'game/:game_id/details' });

    this.route('game', { path: 'game/:game_id' }, function () {
      this.route('broadcaster-language', {path: ':broadcaster_language'});

      this.route('videos', function () {
        this.route('video-type', {path: '/:videoType'});
      });
      this.route('clips');
    });

    this.route('following', function () {
      this.route('games', {path: 'games'});
      this.route('channels', {path: 'live'});
      this.route('videos', function () {
        this.route('video-type', {path: '/:videoType'});
      });
      this.route('hosts', {path: 'hosts'});
    });

    this.route('channels', { path: 'all' }, function () {
      this.route('all', {path: '/'});
      this.route('broadcasterLanguage', {path: ':broadcaster_language'});
      this.route('psFour', {path: 'ps4'});
      this.route('xbOne', {path: 'xb1'});
      this.route('creative', {path: 'creative'});
      this.route('random');
    });

    this.route('videos', function () {
      this.route('video-type', {path: '/:videoType'});
    });

  });

  this.route('email-verification', { path: '/email-verification/:opaque_id' });

  this.route('backpack', { path: 'subscriptions' });

  this.route('broadcast');

  this.route('youtubeRedirect', { path: '/yt/:channel' });

  // Functionality for breakaway; redirects to normal channel route for other IDs
  this.route('streamplus', { path: '/:channel/streamplus' });

  this.route('user', { path: ':channel' }, function () {
    this.route('vod', { resetNamespace: true, path: 'v/:vod' });
    this.route('channel', { resetNamespace: true, path: '' }, function () {
      this.route('index', {path: ''}, function () {
        this.route('post', {path: 'p/:post_id'});
      });

      // this.route('post', {path: 'p/:post_id'});

      // TODO:  These are the future routes, but when CHANNEL_PAGE_REDESIGN experiment is not active, these will redirect to their /profile counterparts below
      this.route('videos', function () {
        this.route('video-type', {path: '/:videoType'});
      });

      this.route('posts');
      this.route('following');
      this.route('followers');
      this.route('clips');
      this.route('collections');

      // TODO:  These are deprecated routes, and are redirected in routes/profile.js once CHANNEL_PAGE_REDESIGN experiment ends.
      this.route('profile', { resetNamespace: true }, function () {
        this.route('pastBroadcasts', {path: 'past_broadcasts'});
        this.route('highlights');
        this.route('following');
        this.route('followers');
        this.route('uploads');
      });
    });

    this.route('dashboards', { resetNamespace: true, path: 'dashboard' }, function () {
      this.route('events', () => {});

      this.route('revenue');

      this.route('stream-key', { path: 'streamkey' });

      this.route('subscription-dash', { path: 'subscription' }, function () {
        this.route('ads');
        this.route('badges');
        this.route('chat-limit', { path: 'chat' });
        this.route('chat-perks', { path: 'chatperks' });
        this.route('bits-onboarding-settings', { path: 'cheer' });
        this.route('bits-tag-settings', { path: 'cheertags' });
        this.route('creative-properties', { path: 'creative' });
        this.route('payments');
        this.route('payout-settings', { path: 'payouts' }, function () {
          this.route('index', { path: '/' });
        });
        this.route('streamline-bounty-settings', { path: 'streamline' });
        this.route('game-commerce-settings', { path: 'game-commerce' });
        this.route('teespring');
        this.route('ticket-information', { path: 'ticket' });
        this.route('video-limit', { path: 'video' });
      });

      this.route('video-stats', function() {
        this.route('overview', { path: '/' });
        this.route('details');
        this.route('video', { path: ':video_id' }, function() {
          this.route('overview', { path: '/' });
          this.route('details');
        });
      });
    });

    this.route('manager', { resetNamespace: true }, function() {
      this.route('highlights');
      this.route('highlighter', { path: ':videoId/highlight' });

      this.route('past-broadcasts', { path: 'past_broadcasts' }, function() {
        this.route('all', { path: '' });
        this.route('expiring');
      });

      this.route('collections', function() {
        this.route('index', { path: '' });
        this.route('edit', { path: ':collection_id' });
      });

      this.route('uploads');
    });
  });

  this.route('friends', function () {
    this.route('list', {path: '/'});
    this.route('requests', {path: 'requests'});
  });

  this.route('communities', function () {
    this.route('community', { path: ':community_name' });
    this.route('create');
    this.route('moderation', { path: ':community_name/moderation' });
    this.route('moderation-log', { path: ':community_name/moderation/log' });
    this.route('moderation-settings', { path: ':community_name/moderation/settings' });
  });

  this.route('create-landing', { path: 'create' });

  this.route('private/embed-components');

  this.route('settings', function () {
    this.route('profile');
    this.route('extensions', function() {
      this.route('index', { path: '' });
      this.route('details', { path: ':extensionId' });
      this.route('configure', { path: ':extensionId/configure' });
    });
  });

  this.route('pr', function() {
    this.route('welcome');
  });

  this.route('404', {path: '/*wildcard'});

  this.route('bits/bundle', { path: 'products/bits' }, function() {
    this.route('asin', { path: ':asin' });
    this.route('ad');
  });

  this.route('videos', { path: '/videos/:video_id' });
});

export default Router;
