#import "FGRouteSimulator.h"
#import "FGStore.h"
#import "FGSpoofer.h"

NSString *const FGRouteSimulationDidChangeNotification = @"FGRouteSimulationDidChangeNotification";

static const double kFGSimulationTick = 0.5; // giây

@interface FGRouteSimulator () {
    CLLocationCoordinate2D *_coords;
    NSUInteger _pointCount;
}

@property (nonatomic, assign) BOOL running;
@property (nonatomic, assign) BOOL paused;
@property (nonatomic, assign) FGTransportType transport;
@property (nonatomic, assign) double speedKPH;
@property (nonatomic, assign) CLLocationDistance totalDistance;
@property (nonatomic, assign) CLLocationDistance traveledDistance;
@property (nonatomic, assign) CLLocationCoordinate2D startCoordinate;
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate;
@property (nonatomic, assign) CLLocationCoordinate2D destinationCoordinate;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger persistCounter;

@end

@implementation FGRouteSimulator

+ (instancetype)shared {
    static FGRouteSimulator *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[FGRouteSimulator alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _transport = FGTransportTypeWalking;
        _speedKPH = [FGStore walkSpeed];
    }
    return self;
}

- (void)dealloc {
    [self clearRoute];
}

- (void)clearRoute {
    if (_coords) {
        free(_coords);
        _coords = NULL;
    }
    _pointCount = 0;
}

- (BOOL)isRunning { return self.running; }
- (BOOL)isPaused { return self.paused; }
- (CLLocationDistance)remainingDistance {
    return MAX(0.0, self.totalDistance - self.traveledDistance);
}

#pragma mark - Lập tuyến

- (void)planFrom:(CLLocationCoordinate2D)from
              to:(CLLocationCoordinate2D)to
       transport:(FGTransportType)transport
      completion:(void (^)(CLLocationDistance, NSTimeInterval, NSString *))completion {

    if (!FGCoordinateValid(from) || !FGCoordinateValid(to)) {
        if (completion) completion(0, 0, @"Toạ độ điểm đầu hoặc điểm đến không hợp lệ.");
        return;
    }

    MKPlacemark *fromPlacemark = [[MKPlacemark alloc] initWithCoordinate:from];
    MKPlacemark *toPlacemark = [[MKPlacemark alloc] initWithCoordinate:to];

    MKMapItem *source = [[MKMapItem alloc] initWithPlacemark:fromPlacemark];
    MKMapItem *destination = [[MKMapItem alloc] initWithPlacemark:toPlacemark];

    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    request.source = source;
    request.destination = destination;
    request.transportType = (transport == FGTransportTypeDriving)
        ? MKDirectionsTransportTypeAutomobile
        : MKDirectionsTransportTypeWalking;
    request.requestsAlternateRoutes = NO;

    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    [directions calculateDirectionsWithCompletionHandler:
     ^(MKDirectionsResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            MKRoute *route = response.routes.firstObject;
            if (!route || error) {
                if (completion) {
                    completion(0, 0, error.localizedDescription ?: @"Không tìm được tuyến đường phù hợp.");
                }
                return;
            }

            [self setRoute:route transport:transport from:from to:to];
            if (completion) {
                completion(route.distance, route.expectedTravelTime, nil);
            }
        });
    }];
}

- (void)setRoute:(MKRoute *)route
       transport:(FGTransportType)transport
            from:(CLLocationCoordinate2D)from
              to:(CLLocationCoordinate2D)to {

    [self clearRoute];

    MKPolyline *polyline = route.polyline;
    _pointCount = polyline.pointCount;
    if (_pointCount == 0) return;

    _coords = malloc(sizeof(CLLocationCoordinate2D) * _pointCount);
    [polyline getCoordinates:_coords range:NSMakeRange(0, _pointCount)];

    self.transport = transport;
    self.speedKPH = (transport == FGTransportTypeDriving) ? [FGStore driveSpeed] : [FGStore walkSpeed];
    self.totalDistance = route.distance;
    self.traveledDistance = 0;
    self.startCoordinate = from;
    self.destinationCoordinate = to;
    self.currentCoordinate = from;
    self.running = NO;
    self.paused = NO;

    [self postChange];
}

#pragma mark - Điều khiển

- (void)start {
    if (_pointCount < 2) return;

    self.running = YES;
    self.paused = NO;
    self.traveledDistance = 0;
    self.currentCoordinate = self.startCoordinate;
    self.persistCounter = 0;

    [self restartTimer];
    [[FGSpoofer shared] updateLiveCoordinate:self.startCoordinate];
    [self postChange];
}

- (void)pause {
    if (!self.running) return;
    self.paused = YES;
    [self.timer invalidate];
    self.timer = nil;
    [self postChange];
}

- (void)resume {
    if (!self.running || !self.paused) return;
    self.paused = NO;
    [self restartTimer];
    [self postChange];
}

- (void)stop {
    [self.timer invalidate];
    self.timer = nil;
    self.running = NO;
    self.paused = NO;
    [self postChange];
}

- (void)stopAndRestoreRealLocation {
    [self stop];
    [[FGSpoofer shared] setSpoofingEnabled:NO];
}

- (void)restartTimer {
    [self.timer invalidate];
    self.timer = [NSTimer timerWithTimeInterval:kFGSimulationTick
                                         target:self
                                       selector:@selector(tick)
                                       userInfo:nil
                                        repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)tick {
    if (!self.running || self.paused || _pointCount < 2) return;

    double metersPerSecond = self.speedKPH / 3.6;
    CLLocationDistance step = metersPerSecond * kFGSimulationTick;

    self.traveledDistance += step;
    if (self.traveledDistance >= self.totalDistance) {
        self.traveledDistance = self.totalDistance;
        self.currentCoordinate = self.destinationCoordinate;
        [self applyCoordinate:self.destinationCoordinate];
        [self stop];
        [[NSNotificationCenter defaultCenter]
            postNotificationName:FGRouteSimulationDidChangeNotification
                          object:self
                        userInfo:@{@"finished": @YES}];
        return;
    }

    CLLocationCoordinate2D coordinate = [self coordinateAtDistance:self.traveledDistance];
    if (!FGCoordinateValid(coordinate)) return;

    self.currentCoordinate = coordinate;
    [self applyCoordinate:coordinate];
}

- (void)applyCoordinate:(CLLocationCoordinate2D)coordinate {
    [[FGSpoofer shared] updateLiveCoordinate:coordinate];

    // Chỉ ghi xuống defaults mỗi ~3 giây để tránh I/O liên tục.
    self.persistCounter++;
    if (self.persistCounter >= 6) {
        self.persistCounter = 0;
        [FGStore setCoordinate:coordinate silent:YES];
    }
    [self postChange];
}

#pragma mark - Nội suy

- (CLLocationCoordinate2D)coordinateAtDistance:(CLLocationDistance)distance {
    if (_pointCount < 2) return self.startCoordinate;

    CLLocationDistance accumulated = 0;
    for (NSUInteger i = 0; i + 1 < _pointCount; i++) {
        CLLocationCoordinate2D a = _coords[i];
        CLLocationCoordinate2D b = _coords[i + 1];
        CLLocationDistance segment = MKMetersBetweenMapPoints(MKMapPointForCoordinate(a),
                                                              MKMapPointForCoordinate(b));

        if (segment <= 0.0001) continue;

        if (accumulated + segment >= distance) {
            double ratio = (distance - accumulated) / segment;
            return FGCoordinateMake(a.latitude + (b.latitude - a.latitude) * ratio,
                                    a.longitude + (b.longitude - a.longitude) * ratio);
        }
        accumulated += segment;
    }

    return self.destinationCoordinate;
}

- (void)postChange {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:FGRouteSimulationDidChangeNotification
                                                            object:self];
    });
}

@end
