import { parseCookie } from 'mweb/common/utils/cookie';
import { ClientRedirectManager } from 'mweb/client/clientRedirectManager';

function redirectToMobileWeb(path: string, cookie: string): void {
  const manager = new ClientRedirectManager(
    path.split('/').slice(1),
    parseCookie(cookie),
    navigator.userAgent,
  );
  if (manager.redirectToMobileWeb()) {
    window.location.replace(window.location.href.replace(/(www|go)/, 'm'));
  }
}
function enhancePushState(): void {
  const originalPushState = history.pushState;
  history.pushState = function newPushState(): void {
    originalPushState.apply(history, arguments);
    redirectToMobileWeb(window.location.pathname, document.cookie);
  };
}

export function setupTrafficSplitting(): void {
  redirectToMobileWeb(window.location.pathname, document.cookie);
  enhancePushState();
}
