#import "UnityAppController.h"
#import "AppDelegateListener.h"
#import <Stove/Stove.h>

// 이 파일은 Stove(필수) 플러그인에 실린다. 인증 딥링크(onOpenURL:·openURL:options:)와
// 씬 구성(configurationForConnectingSceneSession:)은 푸시와 무관하게 필요하므로
// StovePush 패키지로 보낼 수 없다. 그래서 파일은 여기 두고 푸시 부분만 접는다.
#if __has_include(<StovePush/StovePush.h>)
#import <StovePush/StovePush.h>
#define STOVE_HAS_PUSH 1
#else
#define STOVE_HAS_PUSH 0
#endif

#if STOVE_HAS_PUSH
@interface StoveSDKAppController : UnityAppController <SGSPushNotificationCenterDelegate, AppDelegateListener>
#else
@interface StoveSDKAppController : UnityAppController <AppDelegateListener>
#endif
@end

@implementation StoveSDKAppController

- (instancetype)init
{
    self = [super init];
    if (self != nil)
    {
        UnityRegisterAppDelegateListener(self);
    }
    return self;
}

- (void)onOpenURL:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    id urlValue = userInfo[@"url"];

    if (![urlValue isKindOfClass:NSURL.class])
    {
        return;
    }

    NSURL *url = (NSURL *)urlValue;

    void (^handleURL)(void) = ^{
        NSMutableDictionary<UIApplicationOpenURLOptionsKey, id> *options =
            [NSMutableDictionary dictionary];

        id sourceApplication = userInfo[@"sourceApplication"];
        if (sourceApplication != nil &&
            sourceApplication != NSNull.null)
        {
            options[UIApplicationOpenURLOptionsSourceApplicationKey] =
                sourceApplication;
        }

        id annotation = userInfo[@"annotation"];
        if (annotation != nil &&
            annotation != NSNull.null)
        {
            options[UIApplicationOpenURLOptionsAnnotationKey] =
                annotation;
        }

        options[UIApplicationOpenURLOptionsOpenInPlaceKey] = @NO;

        [SGSApplicationDelegate
            application:UIApplication.sharedApplication
            openURL:url
            options:options];
    };

    if (NSThread.isMainThread)
    {
        handleURL();
    }
    else
    {
        dispatch_async(
            dispatch_get_main_queue(),
            handleURL);
    }
}

#if STOVE_HAS_PUSH
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[SGSPushNotificationCenter currentPushNotificationCenter] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
#endif

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    return [SGSApplicationDelegate application:app openURL:url options:options];
}

#if STOVE_HAS_PUSH
- (void)application:(UIApplication *)application
        didReceiveRemoteNotification:(NSDictionary *)userInfo
              fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [[SGSPushNotificationCenter currentPushNotificationCenter] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
#endif

// if (FOREGROUND_NOTIFICATION_ENABLED)
// {
/** Foreground Notification **/
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
#if STOVE_HAS_PUSH
    [[SGSPushNotificationCenter currentPushNotificationCenter] setDelegate:self];
#endif

    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (UISceneConfiguration *)application:(UIApplication *)application
        configurationForConnectingSceneSession:(UISceneSession *)session
                                       options:(UISceneConnectionOptions *)options
{
    return [UISceneConfiguration
        configurationWithName:@"Default Configuration"
        sessionRole:session.role];
}

#if STOVE_HAS_PUSH
/** Foreground Notification **/
- (void)willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    UNNotificationPresentationOptions options = 0;
    
    // ForegroundPushEnabled: 키 없으면 기본 true (포그라운드 푸시 사용)
    NSNumber *foregroundPushSettings = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"ForegroundPushEnabled"];
    BOOL foregroundPushEnabled = (foregroundPushSettings == nil) ? YES : foregroundPushSettings.boolValue;


    // EnablePushListOptions: 키 없으면 기본 true (list 기본 사용)
    NSNumber *pushListOptionEnabled = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"EnablePushListOptions"];
    BOOL enablePushListOptions = (pushListOptionEnabled == nil) ? YES : pushListOptionEnabled.boolValue;
    
    if (foregroundPushEnabled) {
        options |= UNNotificationPresentationOptionSound;
        
        if (@available(iOS 14.0, *)) {
            options |= UNNotificationPresentationOptionBanner;
            if (enablePushListOptions) {
                options |= UNNotificationPresentationOptionList;
            }
        } else {
            options |= UNNotificationPresentationOptionAlert;
        }
    }
    
    completionHandler(options);
}
// }


#endif
@end

IMPL_APP_CONTROLLER_SUBCLASS(StoveSDKAppController)
