//
//  XTLogConsoleHelper.m
//  XTads
//
//  Created by Rune Berg on 23/07/2020.
//  Copyright © 2020 Rune Berg. All rights reserved.
//

#import "XTLogConsoleHelper.h"
#import "XTUIUtils.h"
#import "XTLogger.h"


@implementation XTLogConsoleHelper

static XTLogger* logger;

+ (void)initialize
{
	logger = [XTLogger loggerForClass:[XTLogConsoleHelper class]];
}

+ (void)openLogConsole
{
	XT_DEF_SELNAME;

	NSBundle *mainBundle = [NSBundle mainBundle];
	NSString *scriptName = @"xtads-open-console.scpt";

	NSString *scriptPathString = [mainBundle pathForResource:scriptName ofType:nil];
	if (scriptPathString == nil) {
		NSString *msg = [NSString stringWithFormat:@"Failed to find bundled AppleScript script \"%@\" to open log console.",
						 scriptName];
		XT_ERROR_1(@"%@", msg);
		[XTUIUtils showModalErrorDialogInWindow:nil messageText:msg];
		return;
	}

	NSURL * scriptPathUrl = [NSURL fileURLWithPath:scriptPathString];

	NSDictionary *errorDictInit;
	NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL:scriptPathUrl error:&errorDictInit];
	if (script == nil) {
		NSString *msg = [NSString stringWithFormat:@"Failed to create AppleScript script to open log console.\n\n%@",
						 [self errorCauseMsgForOpenLogConsole:errorDictInit]];
		XT_ERROR_1(@"%@", msg);
		[XTUIUtils showModalErrorDialogInWindow:nil messageText:msg];
		return;
	}
	
	NSDictionary *errorDictExec;
	NSAppleEventDescriptor *eventDescr = [script executeAndReturnError:&errorDictExec];
	if (eventDescr == nil) {
		NSString *msg = [NSString stringWithFormat:@"Failed to execute AppleScript script to open log console.\n\n%@",
						 [self errorCauseMsgForOpenLogConsole:errorDictExec]];
		XT_ERROR_1(@"%@", msg);
		//[XTUIUtils showModalErrorDialogInWindow:nil messageText:msg];
			// On Cataline, we get a "Not authorized to send Apple events to System Events" error
		return;
	}
}

+ (NSString *)errorCauseMsgForOpenLogConsole:(NSDictionary *)errorDict
{
	NSString *msg = errorDict[@"NSAppleScriptErrorBriefMessage"];
	if (msg == nil) {
		msg = errorDict[@"NSAppleScriptErrorMessage"];
	}
	if (msg == nil) {
		msg = @"Unknown reason.";
	}
	return msg;
}
@end
