//
//  SafariWebExtensionHandler.m
//  Redwax SignText Extension
//
//  Created by Graham Leggett on 2022/04/18.
//

#import "SafariWebExtensionHandler.h"

#import <SafariServices/SafariServices.h>

#import <AppKit/AppKit.h>

#include "config.h"

#if __MAC_OS_X_VERSION_MIN_REQUIRED < 110000
NSString * const SFExtensionMessageKey = @"message";
#endif

static NSString* WebEidApp = @ REDWAX_APP_IDENTIFIER;
static NSString* WebEidExtension = @ REDWAX_EXTENSION_IDENTIFIER;
static NSString* WebEidShared = @"ET847QJV9F.eu.web-eid.web-eid-safari.shared";
static NSString* WebEidStarting = @"eu.redwax.rst.Redwax-SignText.starting";

@implementation SafariWebExtensionHandler

static NSUserDefaults* getUserDefaults()
{
    return [[NSUserDefaults alloc] initWithSuiteName:WebEidShared];
}

- (void)beginRequestWithExtensionContext:(NSExtensionContext *)context {
    id message = [context.inputItems.firstObject userInfo][SFExtensionMessageKey];
    NSLog(@"Received message from browser.runtime.sendNativeMessage: %@", message);

    NSURL *appURL = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:WebEidApp];

    if (![NSWorkspace.sharedWorkspace launchApplication:appURL.path]) {
        NSLog(@"web-eid-safari-extension: failed to start app");
        return;
    }

    NSExtensionItem *response = [[NSExtensionItem alloc] init];
    response.userInfo = @{ SFExtensionMessageKey: @{ @"Response to": message } };

    [context completeRequestReturningItems:@[ response ] completionHandler:nil];
}

@end
