import "codable.dart";

class MapLocation implements Codable {  
  final int? time;

  final String? address;

  final double latitude;

  final double longitude;

  final int? errorCode;

  final double? speed;

  final double? bearing;

  MapLocation({
    this.time,
    this.address,
    this.errorCode,
    this.speed,
    this.bearing,
    required this.latitude,
    required this.longitude,
  });

  @override
  Map<String, dynamic> toJson() {
    return {
      'time': time,
      'address': address,
      'latitude': latitude,
      'longitude': longitude,
      'errorCode': errorCode,
      'speed': speed,
      'bearing': bearing,
    };
  }

  factory MapLocation.fromJson(Map<String, dynamic> map) {
    return MapLocation(
      time: map['time'],
      address: map['address'],
      latitude: _parseDouble(map['latitude']),
      longitude: _parseDouble(map['longitude']),
      errorCode: map['errorCode'],
      speed: _parseDouble(map['speed']),
      bearing: _parseDouble(map['bearing']),
    );
  }
  
  // 将任何数值类型（包括整数）强制转换为double
  static double _parseDouble(dynamic value) {
    if (value == null) return 0.0;
    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) return double.tryParse(value) ?? 0.0;
    return 0.0;
  }

  @override
  String toString() {
    return 'MapLocation{time: $time, address: $address, latitude: $latitude, longitude: $longitude, errorCode: $errorCode, speed: $speed, bearing: $bearing}';
  }
}
