import type { IRouter } from './types';

/**
 * 路由跳转时增加 type，防止页面栈混乱
 * @param router 路由
 */
export function interceptRouterInH5(router: IRouter) {
  hookRouter(router, 'push', 'navigateTo');
  hookRouter(router, 'replace', 'redirectTo');
}

function hookRouter(router: IRouter, method: string, type: string) {
  const originFunc = router[method];

  router[method] = function (...args: any) {
    if (args.length === 1
      && typeof args[0] === 'object'
      && args[0].path
    ) {
      return originFunc.call(this, {
        ...args[0],
        type,
      });
    }

    return originFunc.call(this, ...args);
  };
}
