//
//  XTPrefsItemLoglevelByName.m
//  XTads
//
//  Created by Rune Berg on 28/04/2018.
//  Copyright © 2018 Rune Berg. All rights reserved.
//

#import "XTPrefsItemLoglevelByName.h"
#import "XTPrefsItem_private.h"
#import "XTLogConfig.h"


@implementation XTPrefsItemLoglevelByName

+ (instancetype)itemWithDefaultValue:(id)defaultValue
					 userDefaultsKey:(NSString *)userDefaultsKey;
{
	return [XTPrefsItemLoglevelByName itemWithDefaultValue:defaultValue
										   userDefaultsKey:userDefaultsKey
										  valueTransformer:nil];
}

+ (instancetype)itemWithDefaultValue:(id)defaultValue
					 userDefaultsKey:(NSString *)userDefaultsKey
					valueTransformer:(XTPrefsValueTransformer *)valueTransformer
{
	XTPrefsItemLoglevelByName *item = [XTPrefsItemLoglevelByName new];
	item.defaultValue = defaultValue;
	item.userDefaultsKey = userDefaultsKey;
	item.valueTransformer = valueTransformer;
	item.skipResetToDefault = NO;
	item.value = [item copyOfDefaultValue];
	return item;
}

- (id)copyOfDefaultValue
{
	id res = [self.defaultValue mutableCopy];
	return res;
}

- (void)internalPersist:(id)persistedValue
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	NSDictionary *copyOfValue = [self.value copy];
	[userDefaults setObject:copyOfValue forKey:self.userDefaultsKey];
}

- (id)internalRestoreFromPersisted
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	NSDictionary *tempRes = [userDefaults dictionaryForKey:self.userDefaultsKey];
	NSMutableDictionary *res = [tempRes mutableCopy];
	return res;
}

- (void)resetToDefaultValue
{
	NSNumber *defaultLogLevel = [NSNumber numberWithInteger:XT_DEFAULT_LOG_LEVEL];
	NSArray *keys = self.value.allKeys;
	for (NSString *key in keys) {
		self.value[key] = defaultLogLevel;
	}
}

@end
