determineUnitSystem function

Future<bool> determineUnitSystem()

Determines appropriate unit system based on device locale and location

Implementation

Future<bool> determineUnitSystem() async {
  // Default to metric (true)
  bool useMetric = true;

  try {
    // Check if user has explicitly set preference
    if (prefs.containsKey('use_metric_units')) {
      return prefs.getBool('use_metric_units') ?? true;
    }

    // Try to determine based on current location
    final locationService = LocationService();
    final position = await locationService.getCurrentLocation();

    if (position != null) {
      // Check if user is in a country that uses imperial units
      // This would ideally use a geocoding service to determine country
      // For now, use a simple heuristic based on latitude/longitude

      // Approximate US, Liberia, and Myanmar based on bounds
      bool inUS = position.latitude > 24.0 && position.latitude < 50.0 &&
                  position.longitude > -125.0 && position.longitude < -66.0;

      bool inLiberia = position.latitude > 4.0 && position.latitude < 9.0 &&
                      position.longitude > -12.0 && position.longitude < -7.0;

      bool inMyanmar = position.latitude > 9.0 && position.latitude < 29.0 &&
                       position.longitude > 92.0 && position.longitude < 102.0;

      if (inUS || inLiberia || inMyanmar) {
        useMetric = false;
      }
    }

    // Save the determined preference
    await prefs.setBool('use_metric_units', useMetric);
    return useMetric;
  } catch (e) {
    print('Error determining unit system: $e');
    return true; // Default to metric on error
  }
}