import { Route } from 'vue-router/types';
import {
  RouterHistoryPluginOptions,
  RouterHistoryPlugin,
  RouterReplaceFunc,
} from './script/types';
import HistoryStack from './script/classes/HistoryStack';
import optionsValidator from './script/optionsValidator';
import { ErrorHandler, RawLocation } from 'vue-router/types/router';

let originalReplace: RouterReplaceFunc;
/**
 * Плагин для сбора истории роутра
 */
const RouterHistory: RouterHistoryPlugin<RouterHistoryPluginOptions> = {
  history: new HistoryStack(),
  router: null,

  install(_Vue, options) {
    optionsValidator(options);

    if (!options) {
      return;
    }

    this.router = options.router;
    this.router.$history = this.history;
    this.history.updateLimit(options.limit);

    /* Установка обертки для router.replace */
    originalReplace = this.router.replace;
    this.router.replace = (
      location: RawLocation,
      // eslint-disable-next-line @typescript-eslint/ban-types
      onComplete?: Function,
      onAbort?: ErrorHandler
    ) => {
      this.router?.$history?.removeNewest();
      originalReplace.call(this.router, location, onComplete, onAbort);
    };

    /* Установка хуков */
    this.router.afterEach((route: Route) => this.onRouteChange(route));
  },

  /**
   * Действие при изменении роута
   */
  onRouteChange(route) {
    this.history.add(route);
  },
};

export default RouterHistory;
