#import <Flutter/Flutter.h>
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
#import <UserNotifications/UserNotifications.h>

#include "FlutterController.h"

@implementation FlutterController

UnityFramework *unityFrameworkCache;
UIViewController *rootViewController;

FlutterEngine *flutterEngine;
FlutterMethodChannel *flutterChannel;
FlutterViewController *flutterViewController;

- (id) init:(UnityFramework *)unityFramework {
    self = [super init];
    unityFrameworkCache = unityFramework;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUnityNotification:) name:@"unity2flutter" object:nil];
    
    return self;
}

- (void)handleUnityNotification:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    
    if([info objectForKey:@"request_from_client"]) {
        NSString *str = info[@"request_from_client"];
        [flutterChannel invokeMethod:@"client" arguments:str];
        return;
    }
    
    if([info objectForKey:@"unity_initialized"]) {
        rootViewController = [[unityFrameworkCache appController] rootViewController];
        [self initializeFlutter];
    }
    else if([info objectForKey:@"applicationDidEnterBackground"]) {
        if (flutterEngine == nil) return;
        [flutterEngine.lifecycleChannel sendMessage:@"AppLifecycleState.paused"];
    }
    else if([info objectForKey:@"applicationWillEnterForeground"]) {
        if (flutterEngine == nil) return;
        [flutterEngine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"];
    }
    else if([info objectForKey:@"applicationDidBecomeActive"]) {
        if (flutterEngine == nil) return;
        [flutterEngine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"];
    }
    else if([info objectForKey:@"applicationWillResignActive"]) {
        if (flutterEngine == nil) return;
        [flutterEngine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
    }
    else if([info objectForKey:@"applicationWillTerminate"]) {
        if (flutterEngine == nil) return;
        [flutterEngine.lifecycleChannel sendMessage:@"AppLifecycleState.detached"];
    }
}

- (void)initializeFlutter {
    // FlutterEngineのインスタンス作成
    flutterEngine = [[FlutterEngine alloc] initWithName:@"io.flutter" project:nil];
    
    // Flutter初期化時にエントリポイントとなるメソッドを指定
    [flutterEngine runWithEntrypoint:@"main" initialRoute:@"/"];

    // FlutterのPlugin管理のためにEngineをセット
    [GeneratedPluginRegistrant registerWithRegistry:flutterEngine];
    // FlutterEngineのインスタンを使いFlutterViewControllerを作成
    flutterViewController = [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
    flutterViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        
    // UnityのRootViewに対してFlutterViewを表示
    [rootViewController presentViewController:flutterViewController animated:NO completion:nil];
    
}

@end
