1// Copyright 2018-present 650 Industries. All rights reserved.
2
3#import "EXScopedNotificationSchedulerModule.h"
4#import "EXScopedNotificationsUtils.h"
5#import "EXScopedNotificationSerializer.h"
6#import "EXScopedNotificationsUtils.h"
7
8@interface EXScopedNotificationSchedulerModule ()
9
10@property (nonatomic, strong) NSString *scopeKey;
11
12@end
13
14@implementation EXScopedNotificationSchedulerModule
15
16- (instancetype)initWithScopeKey:(NSString *)scopeKey
17{
18  if (self = [super init]) {
19    _scopeKey = scopeKey;
20  }
21
22  return self;
23}
24
25- (UNNotificationRequest *)buildNotificationRequestWithIdentifier:(NSString *)identifier
26                                                          content:(NSDictionary *)contentInput
27                                                          trigger:(NSDictionary *)triggerInput
28{
29  NSString *scopedIdentifier = [EXScopedNotificationsUtils scopedIdentifierFromId:identifier
30                                                                    forExperience:_scopeKey];
31  return [super buildNotificationRequestWithIdentifier:scopedIdentifier content:contentInput trigger:triggerInput];
32}
33
34- (NSArray * _Nonnull)serializeNotificationRequests:(NSArray<UNNotificationRequest *> * _Nonnull) requests;
35{
36  NSMutableArray *serializedRequests = [NSMutableArray new];
37  for (UNNotificationRequest *request in requests) {
38    if ([EXScopedNotificationsUtils isId:request.identifier scopedByExperience:_scopeKey]) {
39      [serializedRequests addObject:[EXScopedNotificationSerializer serializedNotificationRequest:request]];
40    }
41  }
42  return serializedRequests;
43}
44
45
46- (void)cancelNotification:(NSString *)identifier resolve:(EXPromiseResolveBlock)resolve rejecting:(EXPromiseRejectBlock)reject
47{
48  NSString *scopedIdentifier = [EXScopedNotificationsUtils scopedIdentifierFromId:identifier
49                                                                    forExperience:_scopeKey];
50  [super cancelNotification:scopedIdentifier resolve:resolve rejecting:reject];
51}
52
53- (void)cancelAllNotificationsWithResolver:(EXPromiseResolveBlock)resolve rejecting:(EXPromiseRejectBlock)reject
54{
55  __block NSString *scopeKey = _scopeKey;
56  [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
57    NSMutableArray<NSString *> *toRemove = [NSMutableArray new];
58    for (UNNotificationRequest *request in requests) {
59      if ([EXScopedNotificationsUtils isId:request.identifier scopedByExperience:scopeKey]) {
60        [toRemove addObject:request.identifier];
61      }
62    }
63    [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:toRemove];
64    resolve(nil);
65  }];
66}
67
68@end
69