//
//  UserDefaultsUtils.m
//  XTads
//
//  Created by Rune Berg on 25/12/2017.
//  Copyright © 2017 Rune Berg. All rights reserved.
//

#import "XTUserDefaultsUtils.h"
#import "XTLogger.h"

@implementation XTUserDefaultsUtils

static XTLogger* logger;

#define KEY_GAMEWINDOW_FRAME @"XTadsGameWindowFrame"
#define VALUE_FMT_GAMEWINDOW_FRAME "x=%d y=%d w=%d h=%d"

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

+ (void)saveGameWindowPositionAndSize:(NSRect *)winFrame
{
	XT_DEF_SELNAME;
	XT_TRACE_0(@"called");
	
	int x = winFrame->origin.x;
	int y = winFrame->origin.y;
	int w = winFrame->size.width;
	int h = winFrame->size.height;
	
	char frameCString[200];
	sprintf(frameCString, VALUE_FMT_GAMEWINDOW_FRAME, x, y, w, h);
	NSString *frameString = [NSString stringWithUTF8String:frameCString];
	
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	[userDefaults setObject:frameString forKey:KEY_GAMEWINDOW_FRAME];
}

+ (void)readGameWindowPositionAndSize:(NSRect *)winFrame
{
	XT_DEF_SELNAME;
	
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	NSString *frameString = [userDefaults stringForKey:KEY_GAMEWINDOW_FRAME];
	if (frameString != nil) {
		int x, y, w, h;
		int argsParsed = sscanf([frameString UTF8String], VALUE_FMT_GAMEWINDOW_FRAME, &x, &y, &w, &h);
		if (argsParsed == 4) {
			winFrame->origin.x = x;
			winFrame->origin.y = y;
			winFrame->size.width = w;
			winFrame->size.height = h;
		} else {
			XT_WARN_1(@"failed to parse frameString \"%@\"", frameString);
			// Nothing, let the OS decide
		}
	} else {
		XT_WARN_0(@"no frameString in NSUserDefaults");
		// Nothing, let the OS decide
	}
	
}

+ (void)getGameWindowPositionAndSizeNicelyInMiddle:(NSRect *)winFrame
{
	NSRect screenFrame = [[NSScreen mainScreen] visibleFrame];
	CGFloat newHeightPct = 80.0;
	winFrame->size.width = 700;
	winFrame->size.height = screenFrame.size.height * (newHeightPct / 100.0);
	winFrame->origin.x = (screenFrame.size.width / 2.0) - (winFrame->size.width / 2.0);
	winFrame->origin.y = (screenFrame.size.height - winFrame->size.height) / 2.0 + 20;
}

@end
