import 'dart:convert'; import 'package:yumi/shared/data_sources/models/sc_music_mode.dart'; import 'package:yumi/shared/data_sources/sources/local/data_persistence.dart'; class RoomMusicRepository { List loadSongs() { final raw = DataPersistence.getUserRoomMusic(); if (raw.trim().isEmpty) { return []; } try { final decoded = jsonDecode(raw); if (decoded is! List) { return []; } final songs = decoded .map((item) => SCMusicMode.fromJson(item)) .where((item) => item.hasPlayablePath) .toList() ..sort((a, b) { final sort = a.sortIndex.compareTo(b.sortIndex); if (sort != 0) { return sort; } return a.addedAt.compareTo(b.addedAt); }); return _normalizeSort(songs); } catch (_) { return []; } } Future saveSongs(List songs) { final normalized = _normalizeSort(_dedupeSongs(songs)); return DataPersistence.setUserRoomMusic( jsonEncode(normalized.map((item) => item.toJson()).toList()), ); } List _dedupeSongs(List songs) { final seen = {}; final result = []; for (final song in songs) { final key = song.id.isNotEmpty ? song.id : song.localPath; if (key.isEmpty || !seen.add(key)) { continue; } result.add(song); } return result; } List _normalizeSort(List songs) { return List.generate( songs.length, (index) => songs[index].copyWith(sortIndex: index), growable: true, ); } }