//
//  UIApplication+DDCategory.m
//  DDCategoryKit_Private
//
//  Created by 中道 on 2023/2/6.
//

#import "UIApplication+DDCategory.h"

@implementation UIApplication (DDCategory)
@dynamic dd_keyWindow;
@dynamic dd_statusBarFrame;

- (UIWindow *)dd_keyWindow{
    
    static __weak UIWindow *cachedKeyWindow = nil;
    UIWindow *originalKeyWindow = nil;

    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
    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;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        originalKeyWindow = window;
                        break;
                    }
                }
            }
        }
    } else
    #endif
    {
    #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
        originalKeyWindow = [UIApplication sharedApplication].keyWindow;
    #endif
    }

    // app以storyboard启动的时候keyWindow未就绪
    if (originalKeyWindow == nil) {
        #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
        if (@available(iOS 13.0, *)) {
            NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
            for (UIScene *scene in connectedScenes) {
                if ([scene isKindOfClass:[UIWindowScene class]]) {
                    UIWindowScene *windowScene = (UIWindowScene *)scene;
                    originalKeyWindow = windowScene.windows.firstObject;
                    break;
                }
            }
        } else
        #endif
        {
        #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
            originalKeyWindow = [UIApplication sharedApplication].windows.firstObject;
        #endif
        }
    }
    
    //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
    if (originalKeyWindow)
    {
        cachedKeyWindow = originalKeyWindow;
    }
    
    return cachedKeyWindow;
}

- (CGRect)dd_statusBarFrame{
    CGRect statusBarFrame = CGRectZero;
    
    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
    if (@available(iOS 13.0, *)) {
        UIWindow *window = [self dd_keyWindow];
        statusBarFrame = window.windowScene.statusBarManager.statusBarFrame;
    } else
    #endif
    {
    #if __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
        statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
    #endif
    }
    return statusBarFrame;
}

@end
