import hoistNonReactStatics from "hoist-non-react-statics";
import * as React from "react";
import PlatformContext, { PlatformContextType } from "./PlatformContext";
import ShortcutManager from "./ShortcutManager";

export type PlatformProps = {
  manager: ShortcutManager;
  notification: string | null;
  notificationTimestamp: number;
  setNotification: (notificationAndTimestamp: {
    notification: string;
    timestamp: number;
  }) => any;
  showSidebar: boolean;
  setShowSidebar: (showSidebar: boolean) => any;
  showCommandLine: boolean;
  setShowCommandLine: (showCommandLine: boolean) => any;
};

const withPlatform = <P extends object>(Component: React.ComponentType<P>) => {
  type WrappedComponentPropsExceptProvided = Exclude<
    keyof P,
    keyof PlatformProps
  >;
  type ForwardedProps = Pick<P, WrappedComponentPropsExceptProvided>;
  return hoistNonReactStatics(
    class WithShortcutComponent extends React.Component<ForwardedProps> {
      render() {
        return (
          <PlatformContext.Consumer>
            {(PlatformContext: PlatformContextType) => {
              const {
                manager,
                notification,
                setNotification,
                notificationTimestamp,
                showSidebar,
                setShowSidebar,
              } = PlatformContext;
              return (
                <>
                  <Component
                    {...(this.props as P)}
                    manager={manager}
                    notification={notification}
                    notificationTimestamp={notificationTimestamp}
                    setNotification={setNotification}
                    showSidebar={showSidebar}
                    setShowSidebar={setShowSidebar}
                  />
                </>
              );
            }}
          </PlatformContext.Consumer>
        );
      }
    },
    Component
  );
};

export default withPlatform;
