#import <UIKit/UIKit.h>

static float s_keyboardHeight = 0.0f;

@interface CROSSxKeyboardObserver : NSObject
@end

@implementation CROSSxKeyboardObserver

+ (void)load {
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(keyboardWillShow:)
               name:UIKeyboardWillShowNotification
             object:nil];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(keyboardWillHide:)
               name:UIKeyboardWillHideNotification
             object:nil];
}

+ (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    CGRect frame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = frame.size.height;
    if (@available(iOS 11.0, *)) {
        UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
        if (window) height -= window.safeAreaInsets.bottom;
    }
    s_keyboardHeight = (float)(height * [UIScreen mainScreen].scale);
}

+ (void)keyboardWillHide:(NSNotification *)notification {
    s_keyboardHeight = 0.0f;
}

@end

extern "C" float CROSSxKeyboard_GetHeight() {
    return s_keyboardHeight;
}
