import React from 'react';
import hoistStatics from "hoist-non-react-statics";
import {RouterContext} from './context';
import {useLocation, useQuery, useRoute} from './hooks';

export const withRouter = (Component: any, path?: string) => {
  const location = useLocation();
  const query = useQuery();
  const isCurrent = path ? useRoute(path) : false;
  const displayName = `withRouter(${Component.displayName || Component.name})`;
  const C = (props: any) => {
    const { wrappedComponentRef, ...remainingProps } = props;

    return (
      <RouterContext.Consumer>
        {(context: any) => {
          return (
            <Component
              {...remainingProps}
              {...context}
              location={location}
              query={query}
              ref={wrappedComponentRef}
              isCurrent={isCurrent}
            />
          );
        }}
      </RouterContext.Consumer>
    );
  };

  C.displayName = displayName;
  C.WrappedComponent = Component;
  return hoistStatics(C, Component);
};
