import { consoleInfo } from 't-comm/es/log/log';

import { navigateData, type NavType } from './index';


function innerHookRouter(this: any, {
  originFunc,
  type,
  context,
}: {
  originFunc: Function;
  type: NavType;
  context?: any
}, ...args: any[]) {
  const disableSetNavType = args?.[0]?.query?.disableSetNavType;
  if (disableSetNavType != '1') {
    navigateData.setNavType(type);
  }
  return originFunc.call(context, ...args);
}


export function hookVueRouter(router: any, {
  log = false,
  context,
}: {
  log?: boolean
  context?: any
} = {}) {
  const originPush = router.push;
  const originReplace = router.replace;
  const originBack = router.back;
  const originGo = router.go;


  router.push = (...args: any[]) => {
    consoleInfo(log, '[hookVueRouter] push: ', args);
    return innerHookRouter({
      originFunc: originPush,
      type: 'push',
      context: context ?? router,
    }, ...args);
  };


  router.replace = (...args: any[]) => {
    consoleInfo(log, '[hookVueRouter] replace: ', args);
    return innerHookRouter({
      originFunc: originReplace,
      type: 'replace',
      context: context ?? router,
    }, ...args);
  };


  router.back = (...args: any[]) => {
    consoleInfo(log, '[hookVueRouter] back: ', args);
    return innerHookRouter({
      originFunc: originBack,
      type: 'back',
      context: context ?? router,
    }, ...args);
  };


  router.go = function (this: any, ...args: any[]) {
    consoleInfo(log, '[hookVueRouter] go: ', args, this);
    if (args[0] && typeof args[0] === 'number') {
      if (args[0] < 0) {
        navigateData.setNavType('back');
      } else if (args[0] > 0) {
        navigateData.setNavType('push');
      }
    }

    return originGo.call(context ?? router, ...args);
  };
}
