import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';


/*
class GridGenParams {
  final LatLng center;
  final int count;
  final double spacingMeters;

  const GridGenParams({
    required this.center,
    required this.count,
    required this.spacingMeters,
  });
}Future<List<LatLng>> generateGridMarkersIsolate(GridGenParams params) async {
  return compute(_generateGridMarkersOptimized, params);
}

List<LatLng> _generateGridMarkersOptimized(GridGenParams params) {
  final List<LatLng> result = [];
  final Distance distance = const Distance();

  // Pre-calculate the grid dimensions
  final int gridSize = sqrt(params.count).ceil();
  final double halfWidth = (gridSize * params.spacingMeters) / 2;
  final double halfHeight = (gridSize * params.spacingMeters) / 2;

  // Calculate top-left corner of the grid
  final LatLng topLeft = distance.offset(
      distance.offset(params.center, -halfHeight, 0), // south
      -halfWidth, 270 // west
  );

  // Generate grid in batches for better memory management
  const int batchSize = 10000;
  for (int batch = 0; batch < (params.count / batchSize).ceil(); batch++) {
    final int startIdx = batch * batchSize;
    final int endIdx = min((batch + 1) * batchSize, params.count);

    for (int i = startIdx; i < endIdx; i++) {
      final int row = i ~/ gridSize;
      final int col = i % gridSize;

      final double dx = col * params.spacingMeters;
      final double dy = row * params.spacingMeters;

      final LatLng point = distance.offset(
          distance.offset(topLeft, dy, 180), // south
          dx, 90 // east
      );

      result.add(point);
    }
  }

  return result.sublist(0, min(result.length, params.count));
}
*/
class LatLngSimple {
  final double lat;
  final double lng;

  LatLngSimple(this.lat, this.lng);

  Map<String, double> toJson() => {'lat': lat, 'lng': lng};
}


List<LatLngSimple> generateLatLngInIsolate(int count) {
  final Random random = Random();
  const double minLat = 35.610;
  const double maxLat = 36.120;
  const double minLng = 50.190;
  const double maxLng = 51.100;

  return List.generate(count, (_) {
    double lat = minLat + random.nextDouble() * (maxLat - minLat);
    double lng = minLng + random.nextDouble() * (maxLng - minLng);
    return LatLngSimple(lat, lng);
  });
}

Future<List<LatLng>> generateLocationsUsingCompute(int count) async {
  final result = await compute(generateLatLngInIsolate, count);
  return result.map((e) => LatLng(e.lat, e.lng)).toList();
}