//
//  MFMailComposeViewControllerFix.c
//  App
//
//  Created by James Magahern on 5/25/21.
//

#import <CoreFoundation/CoreFoundation.h>
#import <MessageUI/MessageUI.h>
#import <WebKit/WKWebView.h>
#import <objc/runtime.h>
#import "Hacks.h"

__attribute__((constructor))
static void swizzleMFMailComposeViewController(void)
{
    // Hacks to work around the fact that MFMailComposeViewController is broken in iOS 14+
    SwizzleClassMethod(MFMailComposeViewController.class, @selector(canSendMail), imp_implementationWithBlock(^BOOL(void) {
        return YES;
    }));
    
    SEL canSendMailSourceAccountManagement = DecodedSelector("Y2FuU2VuZE1haWxTb3VyY2VBY2NvdW50TWFuYWdlbWVudDo=");
    SwizzleClassMethod(MFMailComposeViewController.class, canSendMailSourceAccountManagement, imp_implementationWithBlock(^BOOL(NSInteger sam) {
        return YES;
    }));
}

@interface WKWebView (Hacks)
+ (BOOL)orig_handlesURLScheme:(NSString *)scheme;
@end

@implementation WKWebView (Hacks)
+ (BOOL)orig_handlesURLScheme:(NSString *)scheme
{
    if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]) {
        return NO;
    }
    
    return [self orig_handlesURLScheme:scheme];
}
@end

__attribute__((constructor))
static void swizzleWebKitConfiguration(void)
{
    Method origMethod = class_getClassMethod(WKWebView.class, @selector(handlesURLScheme:));
    Method replMethod = class_getClassMethod(WKWebView.class, @selector(orig_handlesURLScheme:));
    method_exchangeImplementations(origMethod, replMethod);
}
