var EventEmitter = require('events').EventEmitter;
var $ = require('zepto');

var Router = new EventEmitter();

function _logGoogleAnalyticsPageview() {
  var location = window.location.protocol +
    '//' + window.location.hostname +
    window.location.pathname +
    window.location.search;
  ga('set', 'location', location);
  ga('send', 'pageview');
}

var _pageState = {
  path: window.location.pathname
};

Router.navigateTo = function(path) {
  _pageState = {
    path: path
  };
  window.history.pushState(_pageState, '', path);
  _logGoogleAnalyticsPageview();
  Router.emit('change');
};

Router.replaceUrl = function(path) {
  _pageState = {
    path: path
  };
  window.history.replaceState(_pageState, '', path);
  _logGoogleAnalyticsPageview();
  Router.emit('change');
};

Router.getPath = function() {
  return _pageState.path;
};

$(window).on('popstate', function(evt) {
  if (evt.state) {
    _pageState = evt.state;
    Router.emit('change', _pageState);
  }
});

window.history.replaceState(_pageState, '', document.location.href);

module.exports = Router;
