import 'dart:async';

import 'package:mnemo_cards_common/mnemo_cards_common.dart';
import 'package:rxdart/rxdart.dart';
import 'package:shared_preferences/shared_preferences.dart';

class FavoriteCardsController {
  late final SharedPreferences _sharedPreferences;
  final StreamController<List<String>> controller =
      StreamController.broadcast();
  List<String> _state = [];

  FavoriteCardsController();

  void set state(List<String> cards) {
    _state = cards;
    _sharedPreferences.setStringList(
      'favorites',
      cards.toList(),
    );
    controller.add(_state);
  }

  List<String> get state {
    _state = (_sharedPreferences.getStringList('favorites') ?? []);
    return _state;
  }

  Future<void> init() async {
    _sharedPreferences = await SharedPreferences.getInstance();
  }

  Future<void> switchFavoriteCard(GameCardDto cardDto) async {
    final favorites = _sharedPreferences.getStringList('favorites') ?? [];
    Set<String> updatedFavorites = favorites.toSet();
    if (favorites.contains(cardDto.id.toString())) {
      updatedFavorites.remove(cardDto.id.toString());
    } else {
      updatedFavorites.add(cardDto.id.toString());
    }
    state = updatedFavorites.toList();
  }

  bool isFavoriteCardString(String id) => state.contains(id);

  bool isFavoriteCard(int? id) =>
      id == null ? false : isFavoriteCardString(id.toString());

  Stream<List<String>> get asStream => controller.stream.startWith(_state);
}
