1// Copyright 2018-present 650 Industries. All rights reserved.
2
3#import "EXScopedNotificationPresentationModule.h"
4#import "EXScopedNotificationsUtils.h"
5#import "EXScopedNotificationSerializer.h"
6
7@interface EXScopedNotificationPresentationModule ()
8
9@property (nonatomic, strong) NSString *experienceId;
10
11@end
12
13@implementation EXScopedNotificationPresentationModule
14
15- (instancetype)initWithExperienceId:(NSString *)experienceId
16{
17  if (self = [super init]) {
18    _experienceId = experienceId;
19  }
20
21  return self;
22}
23
24- (NSArray * _Nonnull)serializeNotifications:(NSArray<UNNotification *> * _Nonnull)notifications
25{
26  NSMutableArray *serializedNotifications = [NSMutableArray new];
27  for (UNNotification *notification in notifications) {
28    if ([EXScopedNotificationsUtils shouldNotification:notification beHandledByExperience:_experienceId]) {
29      [serializedNotifications addObject:[EXScopedNotificationSerializer serializedNotification:notification]];
30    }
31  }
32  return serializedNotifications;
33}
34
35- (void)dismissNotificationWithIdentifier:(NSString *)identifier resolve:(UMPromiseResolveBlock)resolve reject:(UMPromiseRejectBlock)reject
36{
37  __block NSString *experienceId = _experienceId;
38  [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
39    for (UNNotification *notification in notifications) {
40      if ([notification.request.identifier isEqual:identifier]) {
41        if ([EXScopedNotificationsUtils shouldNotification:notification beHandledByExperience:experienceId]) {
42          [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[identifier]];
43        }
44        break;
45      }
46    }
47    resolve(nil);
48  }];
49}
50
51- (void)dismissAllNotificationsWithResolver:(UMPromiseResolveBlock)resolve reject:(UMPromiseRejectBlock)reject
52{
53  __block NSString *experienceId = _experienceId;
54  [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
55    NSMutableArray<NSString *> *toDismiss = [NSMutableArray new];
56    for (UNNotification *notification in notifications) {
57      if ([EXScopedNotificationsUtils shouldNotification:notification beHandledByExperience:experienceId]) {
58        [toDismiss addObject:notification.request.identifier];
59      }
60    }
61    [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:toDismiss];
62    resolve(nil);
63  }];
64}
65
66@end
67