#import "VpnProxyDetect.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import <CFNetwork/CFNetwork.h>

@implementation VpnProxyDetect
RCT_EXPORT_MODULE()

- (void)detectVPN:(RCTPromiseResolveBlock)resolve
           reject:(RCTPromiseRejectBlock)reject {
    CFDictionaryRef cfDict = CFNetworkCopySystemProxySettings();
    NSDictionary *nsDict = (__bridge NSDictionary*)cfDict;
    NSDictionary *keys = [nsDict valueForKey:@"__SCOPED__"];
    BOOL isConnected = NO;
    
    if (keys != nil) {
        for (id key in keys) {
            if ([@"tap" isEqual: key] || [@"tun" isEqual: key] || [@"ppp" isEqual: key] || [@"ipsec" isEqual: key] || [@"ipsec0" isEqual: key] || [key containsString: @"utun"]) {
                isConnected = YES;
                break;
            }
        }
    }
    
    if (cfDict) {
        CFRelease(cfDict);
    }
    
    resolve(@(isConnected));
}

- (void)detectProxy:(RCTPromiseResolveBlock)resolve
             reject:(RCTPromiseRejectBlock)reject {
    NSDictionary *proxySettings = CFBridgingRelease(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.google.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    
    BOOL isConnected = NO;
    if (proxies && [proxies count] > 0) {
        NSDictionary *settings = proxies[0];
        if (![[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
            isConnected = YES;
        }
    }
    
    resolve(@(isConnected));
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeVpnProxyDetectSpecJSI>(params);
}

@end
