#import "UINavigationController+HBD.h"

#import <React/RCTLog.h>

@implementation UINavigationController (HBD)

- (void)redirectToViewController:(UIViewController *)controller animated:(BOOL)animated {
    [self redirectToViewController:controller target:self.topViewController animated:animated];
}

- (void)redirectToViewController:(UIViewController *)controller target:(UIViewController *)target animated:(BOOL)animated {
    NSMutableArray *children = [self.childViewControllers mutableCopy];
    NSUInteger index = [children indexOfObject:target];
    if (index == NSNotFound) {
        RCTLogWarn(@"[Navigation] redirectTo target is no longer in the navigation stack. Fallback to topViewController.");
        index = [children indexOfObject:self.topViewController];
    }

    if (index == NSNotFound) {
        RCTLogWarn(@"[Navigation] redirectTo failed because the navigation stack is empty.");
        return;
    }

    NSUInteger count = self.childViewControllers.count;
    [children removeObjectsInRange:NSMakeRange(index, count - index)];
    [children addObject:controller];
    [self setViewControllers:children animated:animated];
}

@end
