#import "TrimsyNotify.h"

@interface TrimsyNotify ()
@property (nonatomic, copy) NSString *pendingTapJs;
@end

@implementation TrimsyNotify

- (void)pluginInitialize {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    if (self.pendingTapJs.length) {
        NSString *js = self.pendingTapJs;
        self.pendingTapJs = nil;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.commandDelegate evalJs:js];
        });
    }
}

- (void)requestPermission:(CDVInvokedUrlCommand *)command {
    UNAuthorizationOptions opts = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
     requestAuthorizationWithOptions:opts
     completionHandler:^(BOOL granted, NSError *error) {
         CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:granted ? 1 : 0];
         [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
     }];
}

- (void)hasPermission:(CDVInvokedUrlCommand *)command {
    [[UNUserNotificationCenter currentNotificationCenter]
     getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
         BOOL ok = settings.authorizationStatus == UNAuthorizationStatusAuthorized
             || settings.authorizationStatus == UNAuthorizationStatusProvisional;
         if (@available(iOS 14.0, *)) {
             ok = ok || settings.authorizationStatus == UNAuthorizationStatusEphemeral;
         }
         CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:ok ? 1 : 0];
         [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
     }];
}

- (void)show:(CDVInvokedUrlCommand *)command {
    [self enqueue:command schedule:NO];
}

- (void)schedule:(CDVInvokedUrlCommand *)command {
    [self enqueue:command schedule:YES];
}

- (void)enqueue:(CDVInvokedUrlCommand *)command schedule:(BOOL)schedule {
    NSDictionary *opts = [command argumentAtIndex:0];
    if (![opts isKindOfClass:[NSDictionary class]]) opts = @{};
    int nid = [self notifyId:opts];
    NSString *title = [NSString stringWithFormat:@"%@", opts[@"title"] ?: @"Trimsy One"];
    NSString *body = [NSString stringWithFormat:@"%@", opts[@"body"] ?: @""];
    NSString *payload = [self payloadString:opts];

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = title;
    content.body = body;
    content.sound = [UNNotificationSound defaultSound];
    content.userInfo = @{ @"payload": payload ?: @"{}" };

    UNNotificationTrigger *trigger = nil;
    if (schedule) {
        double at = [opts[@"at"] doubleValue] / 1000.0;
        NSTimeInterval delay = at - [[NSDate date] timeIntervalSince1970];
        if (delay < 0.15) delay = 0.15;
        trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:delay repeats:NO];
    } else {
        trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.12 repeats:NO];
    }

    NSString *ident = [NSString stringWithFormat:@"%d", nid];
    UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:ident content:content trigger:trigger];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:req withCompletionHandler:^(NSError *error) {
        CDVPluginResult *result = error
            ? [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:(error.localizedDescription ?: @"notify_failed")]
            : [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }];
}

- (void)cancel:(CDVInvokedUrlCommand *)command {
    int nid = [[command argumentAtIndex:0] intValue];
    NSString *ident = [NSString stringWithFormat:@"%d", nid];
    [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[ident]];
    [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[ident]];
    CDVPluginResult *ok = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:ok callbackId:command.callbackId];
}

- (void)cancelAll:(CDVInvokedUrlCommand *)command {
    [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
    [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
    CDVPluginResult *ok = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:ok callbackId:command.callbackId];
}

- (void)openSettings:(CDVInvokedUrlCommand *)command {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    CDVPluginResult *ok = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:ok callbackId:command.callbackId];
}

- (int)notifyId:(NSDictionary *)opts {
    int nid = [opts[@"id"] intValue];
    if (nid == 0) {
        NSString *key = [NSString stringWithFormat:@"%@", opts[@"key"] ?: @""];
        if (key.length == 0) key = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970] * 1000];
        nid = abs((int)[key hash]);
    }
    return nid == 0 ? 1 : nid;
}

- (NSString *)payloadString:(NSDictionary *)opts {
    id extra = opts[@"extra"];
    if ([extra isKindOfClass:[NSDictionary class]] || [extra isKindOfClass:[NSArray class]]) {
        NSData *json = [NSJSONSerialization dataWithJSONObject:extra options:0 error:nil];
        if (json) return [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
    }
    NSString *payload = [NSString stringWithFormat:@"%@", opts[@"payload"] ?: @""];
    if (payload.length && ![payload isEqualToString:@"(null)"]) return payload;
    NSString *extraStr = [NSString stringWithFormat:@"%@", extra ?: @""];
    if (extraStr.length && ![extraStr isEqualToString:@"(null)"]) return extraStr;
    return @"{}";
}

- (void)fireTap:(NSString *)payload {
    NSString *raw = payload.length ? payload : @"{}";
    if (![raw hasPrefix:@"{"] && ![raw hasPrefix:@"["]) {
        NSString *escaped = [[raw stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]
                             stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        raw = [NSString stringWithFormat:@"{\"payload\":\"%@\"}", escaped];
    }
    NSString *js = [NSString stringWithFormat:@"try{cordova.fireDocumentEvent('trimsy-notify',%@);}catch(e){}", raw];
    if (self.webView) {
        [self.commandDelegate evalJs:js];
    } else {
        self.pendingTapJs = js;
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    if (@available(iOS 14.0, *)) {
        completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList | UNNotificationPresentationOptionSound);
    } else {
        completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
    NSString *payload = response.notification.request.content.userInfo[@"payload"];
    [self fireTap:payload];
    completionHandler();
}

@end
