import React, { ComponentType } from 'react';
import { useRouter, useThrottlingLocation } from '../..';
import { RouterProps } from './withRouter';
import { getDisplayName } from '../tools';
import { RouterGenericBase } from '../entities/Types';

export interface ThrottlingRouterProps<R extends RouterGenericBase = RouterGenericBase> extends RouterProps<R> {
  onTransitionEnd: () => void;
}

/**
 * Смотри описание {@link useThrottlingLocation}
 * @param Component
 */
export function withThrottlingRouter<T extends ThrottlingRouterProps<R>, R extends RouterGenericBase = RouterGenericBase>(
  Component: ComponentType<T>
): ComponentType<Omit<T, keyof ThrottlingRouterProps<R>>> {
  function WithThrottlingRouter(props: Omit<T, keyof ThrottlingRouterProps<R>>) {
    const router = useRouter<R>(false);
    const [location, onTransitionEnd] = useThrottlingLocation<R>();
    const routerProps: ThrottlingRouterProps<R> = {
      router: router,
      onTransitionEnd: onTransitionEnd,
      routeState: location.state,
      location: location,
      route: location.route,
    };
    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
    const allProps: T = {
      ...props,
      ...routerProps,
    } as T;
    return <Component {...allProps} />;
  }

  WithThrottlingRouter.displayName = `WithThrottlingRouter(${getDisplayName(Component)})`;
  return WithThrottlingRouter;
}
