import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import '../../contracts/danmaku.dart';
import '../../domain/ports/danmaku_sources_store.dart';


class PrefsDanmakuSourcesStore implements DanmakuSourcesStore {
  static const _keySources = 'smplayer.danmaku_sources';
  static const _keySourceUrl = 'smplayer.danmaku_source_url';

  @override
  Future<List<DanmakuSource>> list() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getStringList(_keySources);
    if (raw == null) return const [];
    final out = <DanmakuSource>[];
    for (final item in raw) {
      try {
        final data = jsonDecode(item);
        if (data is Map<String, dynamic>) {
          final source = DanmakuSource.fromJson(data);
          if (source.url.isNotEmpty) out.add(source);
        }
      } catch (_) {}
    }
    return out;
  }

  @override
  Future<void> replaceAll(List<DanmakuSource> sources) async {
    final prefs = await SharedPreferences.getInstance();
    final serialized = sources
        .where((s) => s.url.trim().isNotEmpty)
        .map((s) => jsonEncode(s.toJson()))
        .toList();
    await prefs.setStringList(_keySources, serialized);
    String? enabledFirst;
    for (final s in sources) {
      if (s.enabled && s.url.trim().isNotEmpty) {
        enabledFirst = s.url;
        break;
      }
    }
    if (enabledFirst == null) {
      await prefs.remove(_keySourceUrl);
    } else {
      await prefs.setString(_keySourceUrl, enabledFirst);
    }
  }
}
