// LocalStorage.mm
#import "LocalStorage.h"

@implementation LocalStorage

+ (NSUserDefaults *)defaults {
    return [NSUserDefaults standardUserDefaults];
}

#pragma mark - Generic Methods

+ (id)loadObjectForKey:(NSString *)key {
    NSData *data = [[self defaults] objectForKey:key];
    if (!data) return nil;

    NSError *error = nil;
    id object = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class],[NSDictionary class],[NSString class],[NSNumber class], nil]
                                                   fromData:data
                                                      error:&error];
    if (error) {
        NSLog(@"Failed to unarchive object for key '%@': %@", key, error);
        return nil;
    }
    return object;
}

+ (void)saveObject:(id)object forKey:(NSString *)key {
    if (!object) return;

    NSError *error = nil;
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object
                                        requiringSecureCoding:NO
                                                        error:&error];
    if (error) {
        NSLog(@"Failed to archive object for key '%@': %@", key, error);
        return;
    }

    [[self defaults] setObject:data forKey:key];
}

+ (void)removeObjectForKey:(NSString *)key {
    [[self defaults] removeObjectForKey:key];
}

#pragma mark - Convenience Array Methods

+ (NSArray *)loadArrayForKey:(NSString *)key {
    id object = [self loadObjectForKey:key];
    if ([object isKindOfClass:[NSArray class]]) {
        return object;
    }
    return nil;
}

+ (void)saveArray:(NSArray *)array forKey:(NSString *)key {
    [self saveObject:array forKey:key];
}

+ (NSDictionary *)loadDictionaryForKey:(NSString *)key {
    id object = [self loadObjectForKey:key];
    if ([object isKindOfClass:[NSDictionary class]]) {
        return object;
    }
    return nil;
}

+ (void)saveDictionary:(NSDictionary *)dict forKey:(NSString *)key {
    [self saveObject:dict forKey:key];
}

@end
