import 'dart:io';
import 'package:latlong2/latlong.dart';

class NoteItemAudio {
  final int? id;
  final int noteItemId;
  final String localPath; // .m4a fájl
  final String caption; // opcionális felirat
  final int durationSeconds; // másodpercben
  final double? latitude;
  final double? longitude;
  final DateTime createdAt;

  const NoteItemAudio({
    this.id,
    required this.noteItemId,
    required this.localPath,
    this.caption = '',
    this.durationSeconds = 0,
    this.latitude,
    this.longitude,
    required this.createdAt,
  });

  File get file => File(localPath);
  bool get fileExists => file.existsSync();
  LatLng? get location => latitude != null && longitude != null
      ? LatLng(latitude!, longitude!)
      : null;

  /// Formázott időtartam: "0:42" vagy "1:23"
  String get durationFormatted {
    final m = durationSeconds ~/ 60;
    final s = (durationSeconds % 60).toString().padLeft(2, '0');
    return '$m:$s';
  }

  NoteItemAudio copyWith({String? caption}) => NoteItemAudio(
        id: id,
        noteItemId: noteItemId,
        localPath: localPath,
        caption: caption ?? this.caption,
        durationSeconds: durationSeconds,
        latitude: latitude,
        longitude: longitude,
        createdAt: createdAt,
      );

  Map<String, dynamic> toMap() => {
        if (id != null) 'id': id,
        'note_item_id': noteItemId,
        'local_path': localPath,
        'caption': caption,
        'duration_seconds': durationSeconds,
        'latitude': latitude,
        'longitude': longitude,
        'created_at': createdAt.toIso8601String(),
      };

  factory NoteItemAudio.fromMap(Map<String, dynamic> m) => NoteItemAudio(
        id: m['id'] as int?,
        noteItemId: m['note_item_id'] as int,
        localPath: m['local_path'] as String,
        caption: m['caption'] as String? ?? '',
        durationSeconds: m['duration_seconds'] as int? ?? 0,
        latitude: (m['latitude'] as num?)?.toDouble(),
        longitude: (m['longitude'] as num?)?.toDouble(),
        createdAt: DateTime.parse(m['created_at'] as String),
      );
}
