import * as React from 'react';
import { ParamListBase } from '@react-navigation/routers';
import NavigationBuilderContext, {
  FocusedNavigationCallback,
  FocusedNavigationListener,
} from './NavigationBuilderContext';
import { NavigationHelpers } from './types';

type Options = {
  navigation: NavigationHelpers<ParamListBase>;
  focusedListeners: FocusedNavigationListener[];
};

/**
 * Hook for passing focus callback to children
 */
export default function useFocusedListenersChildrenAdapter({
  navigation,
  focusedListeners,
}: Options) {
  const { addFocusedListener } = React.useContext(NavigationBuilderContext);

  const listener = React.useCallback(
    (callback: FocusedNavigationCallback<any>) => {
      if (navigation.isFocused()) {
        for (const listener of focusedListeners) {
          const { handled, result } = listener(callback);

          if (handled) {
            return { handled, result };
          }
        }

        return { handled: true, result: callback(navigation) };
      } else {
        return { handled: false, result: null };
      }
    },
    [focusedListeners, navigation]
  );

  React.useEffect(() => addFocusedListener?.(listener), [
    addFocusedListener,
    listener,
  ]);
}
