#import "FGStore.h"

NSString *const FGStoreDidChangeNotification = @"FGStoreDidChangeNotification";
NSString *const FGSpoofStateDidChangeNotification = @"FGSpoofStateDidChangeNotification";
NSString *const FGRequestApplyLocationNotification = @"FGRequestApplyLocationNotification";

NSString *const FGItemName = @"name";
NSString *const FGItemAddress = @"address";
NSString *const FGItemLatitude = @"lat";
NSString *const FGItemLongitude = @"lng";
NSString *const FGItemAltitude = @"altitude";
NSString *const FGItemDate = @"date";

static NSString *const kKeyEnabled = @"FG.Enabled";
static NSString *const kKeyHasCoordinate = @"FG.HasCoordinate";
static NSString *const kKeyLatitude = @"FG.Latitude";
static NSString *const kKeyLongitude = @"FG.Longitude";
static NSString *const kKeyAltitudeEnabled = @"FG.AltitudeEnabled";
static NSString *const kKeyAltitude = @"FG.Altitude";
static NSString *const kKeyPushUpdates = @"FG.PushUpdates";
static NSString *const kKeyFloatingButton = @"FG.FloatingButton";
static NSString *const kKeyButtonX = @"FG.ButtonX";
static NSString *const kKeyButtonY = @"FG.ButtonY";
static NSString *const kKeyGoogleKey = @"FG.GoogleAPIKey";
static NSString *const kKeyCoordMode = @"FG.CoordMode";
static NSString *const kKeyMapStyle = @"FG.MapStyle";
static NSString *const kKeyWalkSpeed = @"FG.WalkSpeed";
static NSString *const kKeyDriveSpeed = @"FG.DriveSpeed";
static NSString *const kKeySaved = @"FG.SavedLocations";
static NSString *const kKeyHistory = @"FG.History";

@implementation FGStore

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

+ (void)notify:(BOOL)spoofStateChanged {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:FGStoreDidChangeNotification object:nil];
        if (spoofStateChanged) {
            [[NSNotificationCenter defaultCenter] postNotificationName:FGSpoofStateDidChangeNotification object:nil];
        }
    });
}

#pragma mark - Trạng thái

+ (BOOL)isEnabled {
    return [[self defaults] boolForKey:kKeyEnabled];
}

+ (void)setEnabled:(BOOL)enabled {
    [[self defaults] setBool:enabled forKey:kKeyEnabled];
    [[self defaults] synchronize];
    [self notify:YES];
}

+ (BOOL)hasCoordinate {
    BOOL has = [[self defaults] boolForKey:kKeyHasCoordinate];
    CLLocationCoordinate2D c = [self coordinate];
    return has && FGCoordinateValid(c);
}

+ (CLLocationCoordinate2D)coordinate {
    double lat = [[self defaults] doubleForKey:kKeyLatitude];
    double lng = [[self defaults] doubleForKey:kKeyLongitude];
    return FGCoordinateMake(lat, lng);
}

+ (void)setCoordinate:(CLLocationCoordinate2D)coordinate {
    [self setCoordinate:coordinate silent:NO];
}

+ (void)setCoordinate:(CLLocationCoordinate2D)coordinate silent:(BOOL)silent {
    NSUserDefaults *d = [self defaults];
    [d setDouble:coordinate.latitude forKey:kKeyLatitude];
    [d setDouble:coordinate.longitude forKey:kKeyLongitude];
    [d setBool:FGCoordinateValid(coordinate) forKey:kKeyHasCoordinate];
    [d synchronize];
    if (!silent) [self notify:YES];
    else dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:FGSpoofStateDidChangeNotification object:nil];
    });
}

+ (NSInteger)coordMode {
    NSUserDefaults *d = [self defaults];
    if ([d objectForKey:kKeyCoordMode] == nil) return 0;
    return [d integerForKey:kKeyCoordMode] == 1 ? 1 : 0;
}

+ (void)setCoordMode:(NSInteger)mode {
    [[self defaults] setInteger:(mode == 1 ? 1 : 0) forKey:kKeyCoordMode];
    [[self defaults] synchronize];
    [self notify:YES];
}

+ (NSInteger)mapStyle {
    return [[self defaults] integerForKey:kKeyMapStyle];
}

+ (void)setMapStyle:(NSInteger)style {
    [[self defaults] setInteger:MAX(0, MIN(2, style)) forKey:kKeyMapStyle];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (double)walkSpeed {
    double value = [[self defaults] doubleForKey:kKeyWalkSpeed];
    return (value >= 1.0 && value <= 12.0) ? value : 5.0;
}

+ (void)setWalkSpeed:(double)kmh {
    [[self defaults] setDouble:MAX(1.0, MIN(12.0, kmh)) forKey:kKeyWalkSpeed];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (double)driveSpeed {
    double value = [[self defaults] doubleForKey:kKeyDriveSpeed];
    return (value >= 5.0 && value <= 240.0) ? value : 40.0;
}

+ (void)setDriveSpeed:(double)kmh {
    [[self defaults] setDouble:MAX(5.0, MIN(240.0, kmh)) forKey:kKeyDriveSpeed];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (BOOL)isAltitudeEnabled {
    return [[self defaults] boolForKey:kKeyAltitudeEnabled];
}

+ (void)setAltitudeEnabled:(BOOL)enabled {
    [[self defaults] setBool:enabled forKey:kKeyAltitudeEnabled];
    [[self defaults] synchronize];
    [self notify:YES];
}

+ (double)altitude {
    double value = [[self defaults] doubleForKey:kKeyAltitude];
    if (isnan(value) || isinf(value) || value < -500.0 || value > 20000.0) {
        return 25.0;
    }
    return value;
}

+ (void)setAltitude:(double)altitude {
    if (isnan(altitude) || isinf(altitude)) altitude = 25.0;
    altitude = MAX(-500.0, MIN(20000.0, altitude));
    [[self defaults] setDouble:altitude forKey:kKeyAltitude];
    [[self defaults] synchronize];
    [self notify:YES];
}

+ (BOOL)pushUpdatesEnabled {
    NSUserDefaults *d = [self defaults];
    if ([d objectForKey:kKeyPushUpdates] == nil) return YES; // mặc định bật
    return [d boolForKey:kKeyPushUpdates];
}

+ (void)setPushUpdatesEnabled:(BOOL)enabled {
    [[self defaults] setBool:enabled forKey:kKeyPushUpdates];
    [[self defaults] synchronize];
    [self notify:YES];
}

#pragma mark - Giao diện

+ (BOOL)floatingButtonEnabled {
    NSUserDefaults *d = [self defaults];
    if ([d objectForKey:kKeyFloatingButton] == nil) return YES;
    return [d boolForKey:kKeyFloatingButton];
}

+ (void)setFloatingButtonEnabled:(BOOL)enabled {
    [[self defaults] setBool:enabled forKey:kKeyFloatingButton];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (CGPoint)floatingButtonPosition {
    NSUserDefaults *d = [self defaults];
    double x = [d objectForKey:kKeyButtonX] ? [d doubleForKey:kKeyButtonX] : 0.86;
    double y = [d objectForKey:kKeyButtonY] ? [d doubleForKey:kKeyButtonY] : 0.72;
    return CGPointMake(MAX(0.06, MIN(0.94, x)), MAX(0.10, MIN(0.90, y)));
}

+ (void)setFloatingButtonPosition:(CGPoint)position {
    NSUserDefaults *d = [self defaults];
    [d setDouble:MAX(0.06, MIN(0.94, position.x)) forKey:kKeyButtonX];
    [d setDouble:MAX(0.10, MIN(0.90, position.y)) forKey:kKeyButtonY];
}

#pragma mark - Google

+ (NSString *)googleAPIKey {
    NSString *key = [[self defaults] stringForKey:kKeyGoogleKey];
    return key.length ? key : nil;
}

+ (void)setGoogleAPIKey:(NSString *)key {
    [[self defaults] setObject:(key ?: @"") forKey:kKeyGoogleKey];
    [[self defaults] synchronize];
    [self notify:NO];
}

#pragma mark - Địa điểm đã lưu

+ (NSArray<NSDictionary *> *)savedLocations {
    id array = [[self defaults] arrayForKey:kKeySaved];
    return [array isKindOfClass:[NSArray class]] ? array : @[];
}

+ (void)addSavedLocation:(NSDictionary *)item {
    if (!item) return;
    NSMutableArray *items = [[self savedLocations] mutableCopy];
    [items insertObject:item atIndex:0];
    [[self defaults] setObject:items forKey:kKeySaved];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (void)removeSavedLocationAtIndex:(NSUInteger)index {    NSMutableArray *items = [[self savedLocations] mutableCopy];
    if (index < items.count) {
        [items removeObjectAtIndex:index];
        [[self defaults] setObject:items forKey:kKeySaved];
        [[self defaults] synchronize];
        [self notify:NO];
    }
}

+ (void)updateSavedLocationAtIndex:(NSUInteger)index name:(NSString *)name {
    NSMutableArray *items = [[self savedLocations] mutableCopy];
    if (index < items.count) {
        NSMutableDictionary *item = [items[index] mutableCopy];
        item[FGItemName] = name ?: @"";
        items[index] = item;
        [[self defaults] setObject:items forKey:kKeySaved];
        [[self defaults] synchronize];
        [self notify:NO];
    }
}

+ (void)clearSavedLocations {
    [[self defaults] removeObjectForKey:kKeySaved];
    [[self defaults] synchronize];
    [self notify:NO];
}

#pragma mark - Lịch sử

+ (NSArray<NSDictionary *> *)historyItems {
    id array = [[self defaults] arrayForKey:kKeyHistory];
    return [array isKindOfClass:[NSArray class]] ? array : @[];
}

+ (void)addHistoryItem:(NSDictionary *)item {
    if (!item) return;
    NSMutableArray *items = [[self historyItems] mutableCopy];

    // Gộp các lần áp dụng cùng toạ độ trong 60 giây để lịch sử không bị rác.
    NSDictionary *last = items.firstObject;
    if (last) {
        double latency = [item[FGItemLatitude] doubleValue];
        double lngency = [item[FGItemLongitude] doubleValue];
        double dlat = fabs([last[FGItemLatitude] doubleValue] - latency);
        double dlng = fabs([last[FGItemLongitude] doubleValue] - lngency);
        NSDate *lastDate = last[FGItemDate];
        if (dlat < 0.00001 && dlng < 0.00001 &&
            [lastDate isKindOfClass:[NSDate class]] &&
            [[NSDate date] timeIntervalSinceDate:lastDate] < 60.0) {
            [items removeObjectAtIndex:0];
        }
    }

    [items insertObject:item atIndex:0];
    if (items.count > 300) {
        [items removeObjectsInRange:NSMakeRange(300, items.count - 300)];
    }
    [[self defaults] setObject:items forKey:kKeyHistory];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (void)removeHistoryItemAtIndex:(NSUInteger)index {
    NSMutableArray *items = [[self historyItems] mutableCopy];
    if (index < items.count) {
        [items removeObjectAtIndex:index];
        [[self defaults] setObject:items forKey:kKeyHistory];
        [[self defaults] synchronize];
        [self notify:NO];
    }
}

+ (void)clearHistory {
    [[self defaults] removeObjectForKey:kKeyHistory];
    [[self defaults] synchronize];
    [self notify:NO];
}

+ (void)resetEverything {
    NSUserDefaults *d = [self defaults];
    for (NSString *key in @[kKeyEnabled, kKeyHasCoordinate, kKeyLatitude, kKeyLongitude,
                            kKeyAltitudeEnabled, kKeyAltitude, kKeyPushUpdates,
                            kKeyGoogleKey, kKeySaved, kKeyHistory,
                            kKeyCoordMode, kKeyMapStyle, kKeyWalkSpeed, kKeyDriveSpeed]) {
        [d removeObjectForKey:key];
    }
    [[self defaults] synchronize];
    [self notify:YES];
}

@end
