#import "CheckApps.h"
#import <React/RCTLog.h>

@implementation CheckApps

RCT_EXPORT_MODULE();

RCT_REMAP_METHOD(getInstalledApps,
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  NSArray *appSchemes = @[
    @{@"appName": @"WhatsApp", @"scheme": @"whatsapp://"},
    @{@"appName": @"Facebook", @"scheme": @"fb://"},
    @{@"appName": @"Twitter", @"scheme": @"twitter://"},
    @{@"appName": @"Instagram", @"scheme": @"instagram://"},
  ];

 
  NSMutableArray *installedApps = [NSMutableArray new];

  dispatch_async(dispatch_get_main_queue(), ^{
    for (NSDictionary *app in appSchemes) {
      NSString *appName = app[@"appName"];
      NSString *scheme = app[@"scheme"];
      NSURL *url = [NSURL URLWithString:scheme];

      if ([[UIApplication sharedApplication] canOpenURL:url])  {
        [installedApps addObject:@{
          @"appName": appName,
          @"scheme": scheme,
          @"packageName": scheme, // for consistency with Android
          @"matchedWith": appName // if needed
        }];
      }
    }
    resolve(installedApps);
  });
}
@end
