#import "TrimsyCalendar.h"

@interface TrimsyCalendar ()
@property (nonatomic, strong) EKEventStore *store;
@property (nonatomic, copy) NSString *pendingCallbackId;
@end

@implementation TrimsyCalendar

- (void)pluginInitialize {
    self.store = [[EKEventStore alloc] init];
}

- (void)insert:(CDVInvokedUrlCommand *)command {
    NSDictionary *event = [command argumentAtIndex:0];
    if (![event isKindOfClass:[NSDictionary class]]) {
        CDVPluginResult *fail = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"missing_event"];
        [self.commandDelegate sendPluginResult:fail callbackId:command.callbackId];
        return;
    }
    self.pendingCallbackId = command.callbackId;
    void (^afterAccess)(BOOL, NSError *) = ^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!granted) {
                [self openFallback:event];
                return;
            }
            [self presentEditor:event];
        });
    };
    if (@available(iOS 17.0, *)) {
        [self.store requestFullAccessToEventsWithCompletion:afterAccess];
    } else {
        [self.store requestAccessToEntityType:EKEntityTypeEvent completion:afterAccess];
    }
}

- (void)presentEditor:(NSDictionary *)payload {
    EKEvent *ek = [EKEvent eventWithEventStore:self.store];
    ek.title = [NSString stringWithFormat:@"%@", payload[@"title"] ?: @""];
    ek.notes = [NSString stringWithFormat:@"%@", payload[@"description"] ?: @""];
    ek.location = [NSString stringWithFormat:@"%@", payload[@"location"] ?: @""];
    double startMs = [payload[@"start"] doubleValue];
    double endMs = [payload[@"end"] doubleValue];
    NSDate *start = startMs > 0 ? [NSDate dateWithTimeIntervalSince1970:(startMs / 1000.0)] : [NSDate date];
    NSDate *end = endMs > startMs ? [NSDate dateWithTimeIntervalSince1970:(endMs / 1000.0)]
                                  : [start dateByAddingTimeInterval:30 * 60];
    ek.startDate = start;
    ek.endDate = end;
    ek.calendar = self.store.defaultCalendarForNewEvents;

    EKEventEditViewController *editor = [[EKEventEditViewController alloc] init];
    editor.eventStore = self.store;
    editor.event = ek;
    editor.editViewDelegate = self;
    [self.viewController presentViewController:editor animated:YES completion:nil];
}

- (void)openFallback:(NSDictionary *)payload {
    NSString *url = [NSString stringWithFormat:@"%@", payload[@"url"] ?: @""];
    if (url.length > 0) {
        NSURL *nsurl = [NSURL URLWithString:url];
        if (nsurl) {
            [[UIApplication sharedApplication] openURL:nsurl options:@{} completionHandler:nil];
            [self finishOk];
            return;
        }
    }
    if (!self.pendingCallbackId) return;
    CDVPluginResult *fail = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"denied"];
    [self.commandDelegate sendPluginResult:fail callbackId:self.pendingCallbackId];
    self.pendingCallbackId = nil;
}

- (void)finishOk {
    if (!self.pendingCallbackId) return;
    CDVPluginResult *ok = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:ok callbackId:self.pendingCallbackId];
    self.pendingCallbackId = nil;
}

- (void)eventEditViewController:(EKEventEditViewController *)controller
          didCompleteWithAction:(EKEventEditViewAction)action {
    [controller dismissViewControllerAnimated:YES completion:^{
        [self finishOk];
    }];
}

@end
