class MeasuredPoint {
  final int? id;
  final int projectId;
  final String name;
  final double? eovY;
  final double? eovX;
  final double? eovZ;
  final double? latitude;
  final double? longitude;
  final double? altitude;
  final double? accuracy;
  final int? fixQuality;
  final DateTime timestamp;
  final String note;

  const MeasuredPoint({
    this.id,
    required this.projectId,
    required this.name,
    this.eovY,
    this.eovX,
    this.eovZ,
    this.latitude,
    this.longitude,
    this.altitude,
    this.accuracy,
    this.fixQuality,
    required this.timestamp,
    this.note = '',
  });

  Map<String, dynamic> toMap() => {
        if (id != null) 'id': id,
        'project_id': projectId,
        'name': name,
        'eov_y': eovY,
        'eov_x': eovX,
        'eov_z': eovZ,
        'latitude': latitude,
        'longitude': longitude,
        'altitude': altitude,
        'accuracy': accuracy,
        'fix_quality': fixQuality,
        'timestamp': timestamp.toIso8601String(),
        'note': note,
      };

  factory MeasuredPoint.fromMap(Map<String, dynamic> m) => MeasuredPoint(
        id: m['id'] as int?,
        projectId: m['project_id'] as int,
        name: m['name'] as String,
        eovY: (m['eov_y'] as num?)?.toDouble(),
        eovX: (m['eov_x'] as num?)?.toDouble(),
        eovZ: (m['eov_z'] as num?)?.toDouble(),
        latitude: (m['latitude'] as num?)?.toDouble(),
        longitude: (m['longitude'] as num?)?.toDouble(),
        altitude: (m['altitude'] as num?)?.toDouble(),
        accuracy: (m['accuracy'] as num?)?.toDouble(),
        fixQuality: m['fix_quality'] as int?,
        timestamp: DateTime.parse(m['timestamp'] as String),
        note: m['note'] as String? ?? '',
      );

  // ── CSV sor ───────────────────────────────────────────────────────

  static String csvHeader() => 'Név;EOV Y;EOV X;EOV Z (tszf);'
      'Lat (WGS84);Lon (WGS84);Magasság (m);'
      'Pontosság (m);Fix minőség;Megjegyzés;Időbélyeg';

  String toCsvRow() {
    String fmt(double? v, int dec) => v == null ? '' : v.toStringAsFixed(dec);
    return '${_csv(name)};'
        '${fmt(eovY, 1)};${fmt(eovX, 1)};${fmt(eovZ, 3)};'
        '${fmt(latitude, 8)};${fmt(longitude, 8)};${fmt(altitude, 3)};'
        '${fmt(accuracy, 4)};${fixQuality ?? ""};'
        '${_csv(note)};${timestamp.toIso8601String()}';
  }

  /// Pontosvesszőt tartalmazó mezőket idézőjelbe teszi
  String _csv(String v) => v.contains(';') ? '"$v"' : v;
}
