






#import "XXGWindowManager.h"
#import "XXGOrientationViewController.h"
#import "XXGPlayKitConfig.h"

@interface XXGWindowManager()
@property (nonatomic, strong) NSMutableArray<UIWindow *> *windowsNoStack;  
@property (nonatomic, strong) NSMutableArray<UIWindow *> *windowsStack;  
@end

@implementation XXGWindowManager

- (instancetype)init {
    self = [super init];
    if (self) {
        _windowsNoStack = [NSMutableArray array];
        _windowsStack = [NSMutableArray array];
    }
    return self;
}

+ (instancetype)shared {
    static id shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[super alloc] init];
    });
    return shared;
}


- (UIWindow *)xxpk_firstWindow {
    UIWindow *firstWindow = nil;
    
    if (@available(iOS 13.0, *)) {
        
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                
                if (windowScene.windows.count > 0) {
                    firstWindow = windowScene.windows.firstObject;
                }
                break;
            }
        }
    } else {
        
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        if (windows.count > 0) {
            firstWindow = windows.firstObject;
        }
    }
    
    
    if (!firstWindow) {
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        if (windows.count > 0) {
            firstWindow = windows.firstObject;
        }
    }
    
    return firstWindow;
}


- (UIWindow *)xxpk_currentWindow {
    
    UIWindow *currentWindow = nil;
    
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                
                
                if (@available(iOS 15.0, *)) {
                    currentWindow = windowScene.keyWindow;
                }
                
                else {
                    for (UIWindow *window in windowScene.windows) {
                        if (window.isKeyWindow) {
                            currentWindow = window;
                            break;
                        }
                    }
                }
                break;
            }
        }
    } else {
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        currentWindow = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
    }
    
    
    if (!currentWindow) {
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *window in windows) {
            if (window.isKeyWindow) {
                currentWindow = window;
                break;
            }
        }
    }
    
    return currentWindow;
}


- (void)__xxpk_showNoStackWindowWithRootViewController:(UIViewController *)rootVC{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            
            UIWindow *newWindow = [self createWindowWithRootVC:rootVC];
            
            
            [self configureWindowDisplay:newWindow];
            
            [self.windowsNoStack addObject:newWindow];
        } else {
            
            __weak typeof(self) weakSelf = self;
            
            __block __weak id obs = nil;
            
            obs = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
                                                                       object:nil
                                                                        queue:[NSOperationQueue mainQueue]
                                                                   usingBlock:^(NSNotification *note) {
                
                [[NSNotificationCenter defaultCenter] removeObserver:obs];
                [weakSelf __xxpk_showNoStackWindowWithRootViewController:rootVC];
            }];
        }
    });
}

- (void)xxpk_showWindowWithRootViewController:(UIViewController *)rootVC {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self xxpk_actuallyCreateWindowWithObject:rootVC];
        } else {
            
            __weak typeof(self) weakSelf = self;
            
            __block __weak id obs = nil;
            
            obs = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
                                                                       object:nil
                                                                        queue:[NSOperationQueue mainQueue]
                                                                   usingBlock:^(NSNotification *note) {
                
                [[NSNotificationCenter defaultCenter] removeObserver:obs];
                
                [weakSelf xxpk_actuallyCreateWindowWithObject:rootVC];
            }];
        }
    });
}

- (void)xxpk_showWindowWithRootView:(UIView *)view {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self xxpk_actuallyCreateWindowWithObject:view];
        } else {
            
            __weak typeof(self) weakSelf = self;
            
            __block __weak id obs = nil;
            
            obs = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
                                                                       object:nil
                                                                        queue:[NSOperationQueue mainQueue]
                                                                   usingBlock:^(NSNotification *note) {
                
                [[NSNotificationCenter defaultCenter] removeObserver:obs];
                
                [weakSelf xxpk_actuallyCreateWindowWithObject:view];
            }];
        }
    });
}

- (void)xxpk_actuallyCreateWindowWithObject:(id)object {
    UIViewController *rootVC = nil;
    
        
    if ([object isKindOfClass:[UIViewController class]]) {
        rootVC = object;
    }
    
    if ([object isKindOfClass:[UIView class]]) {
        rootVC = [XXGOrientationViewController new];
        rootVC.view = object;
    }
    
    
    UIWindow *newWindow = [self createWindowWithRootVC:rootVC];
    
    
    [self configureWindowDisplay:newWindow];
    
    
    [self.windowsStack addObject:newWindow];
}

- (void)xxpk_onDidBecomeActiveOnce:(NSNotification *)note {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationDidBecomeActiveNotification
                                                  object:nil];
    [self xxpk_showWindowWithRootView:note.object];
}

- (void)xxpk_dismissWindow {
    [self xxpk_dismissLastWindow];
}

- (void)xxpk_dismissLastWindow {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.windowsStack.count == 0) return;

        
        UIWindow *lastWindow = [self.windowsStack lastObject];
        [self.windowsStack removeLastObject];

        
        if (lastWindow.isKeyWindow) {
            [self restoreHostKeyWindow];
        }

        
        lastWindow.hidden = YES;
        
        
        for (UIView *subview in [lastWindow.subviews copy]) {
            [subview removeFromSuperview];
        }
        
        
        lastWindow.rootViewController = nil;
        
        
        [CATransaction flush];
        
        
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
    });
}

- (void)xxpk_dismissWindowWithRootViewController:(UIViewController *)rootViewController {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSEnumerator *reverseEnumerator = [self.windowsStack reverseObjectEnumerator];
        UIWindow *window = nil;
        
        
        while ((window = [reverseEnumerator nextObject])) {
            if (window.rootViewController == rootViewController) {
                
                if (window.isKeyWindow) {
                    [self restoreHostKeyWindow];
                }
                
                
                window.hidden = YES;
                
                
                for (UIView *subview in [window.subviews copy]) {
                    [subview removeFromSuperview];
                }
                
                
                window.rootViewController = nil;
                
                [self.windowsStack removeObject:window];
                
                
                [CATransaction flush];
                
                
                [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
                
                
                reverseEnumerator = [self.windowsStack reverseObjectEnumerator];
            }
        }
    });
}

- (void)xxpk_dismissAllWindows {
    dispatch_async(dispatch_get_main_queue(), ^{
        
        for (UIWindow *window in [self.windowsStack reverseObjectEnumerator]) {
            if (window.isKeyWindow) {
                [self restoreHostKeyWindow];
            }
            window.hidden = YES;
            
            
            for (UIView *subview in [window.subviews copy]) {
                [subview removeFromSuperview];
            }
            
            
            window.rootViewController = nil;
        }
        
        
        [self.windowsStack removeAllObjects];
        
        
        [CATransaction flush];
        
        
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
    });
}

- (void)xxpk_dismissAllWindowsWithCompletion:(void(^)(void))completion {
    
    if (self.windowsStack.count == 0) {
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion();
            });
        }
        return;
    }
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSArray *windowsToRemove = [self.windowsStack copy];
        for (UIWindow *window in windowsToRemove) {
            if (window.isKeyWindow) {
                [self restoreHostKeyWindow];
            }
            window.hidden = YES;
            
            
            for (UIView *subview in [window.subviews copy]) {
                [subview removeFromSuperview];
            }
            
            
            window.rootViewController = nil;
        }
        
        
        [self.windowsStack removeAllObjects];
        
        
        [CATransaction flush];
        
        
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (completion) {
                completion();
            }
        });
    });
}


- (UIWindow *)createWindowWithRootVC:(UIViewController *)rootVC {
    UIWindow *window = nil;
    
    
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];
                break;
            }
        }
    }
    
    
    if (!window) {
        window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    
    
    window.backgroundColor = [UIColor clearColor];
    window.rootViewController = rootVC;
    return window;
}

- (void)configureWindowDisplay:(UIWindow *)window {
    

    window.windowLevel = UIWindowLevelStatusBar + 100;
    [window makeKeyAndVisible];
}


- (void)restoreHostKeyWindow {
    UIWindow *hostWindow = [self findHostKeyWindow];
    [hostWindow makeKeyWindow];
    if (!hostWindow.isKeyWindow) {
        [hostWindow becomeKeyWindow];
    }
}

- (UIWindow *)findHostKeyWindow {
    __block UIWindow *hostWindow = nil;
    
    
    if (@available(iOS 13.0, *)) {
        NSArray<UIWindowScene *> *windowScenes = [self activeWindowScenes];
        [windowScenes enumerateObjectsUsingBlock:^(UIWindowScene * _Nonnull scene, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (@available(iOS 15.0, *)) {
                hostWindow = scene.keyWindow;
            }
            
            if (!hostWindow) {
                hostWindow = [scene.windows firstObject];
            }
            if (hostWindow) *stop = YES;
        }];
    }
    
    else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        hostWindow = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
    }
    
    
    if (!hostWindow) {
        hostWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    return hostWindow;
}

- (NSArray<UIWindowScene *> *)activeWindowScenes {
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(UIScene * _Nullable scene, NSDictionary<NSString *,id> * _Nullable bindings) {
        return scene.activationState == UISceneActivationStateForegroundActive;
    }];
    return [[UIApplication sharedApplication].connectedScenes filteredSetUsingPredicate:predicate].allObjects;
}


- (UIWindow *)topWindow {
    return [self.windowsStack lastObject];
}

- (NSInteger)windowCount {
    return self.windowsStack.count;
}


@end
