import 'package:flutter/foundation.dart';
import 'package:result_monad/result_monad.dart';

import '../friendica_client/friendica_client.dart';
import '../globals.dart';
import '../models/auth/profile.dart';
import '../models/connection.dart';
import '../models/exec_error.dart';
import 'auth_service.dart';

class InteractionsManager extends ChangeNotifier {
  final _likesByStatusId = <String, List<Connection>>{};
  final _resharesByStatusId = <String, List<Connection>>{};

  final Profile profile;

  InteractionsManager(this.profile);

  void clear() {
    _likesByStatusId.clear();
    _resharesByStatusId.clear();
    notifyListeners();
  }

  List<Connection> getLikes(String statusId) {
    if (!_likesByStatusId.containsKey(statusId)) {
      updateLikesForStatus(statusId);
      return [];
    }

    return _likesByStatusId[statusId]!;
  }

  List<Connection> getReshares(String statusId) {
    if (!_resharesByStatusId.containsKey(statusId)) {
      updateResharesForStatus(statusId);
      return [];
    }

    return _resharesByStatusId[statusId]!;
  }

  FutureResult<List<Connection>, ExecError> updateLikesForStatus(
      String statusId) async {
    final likesResult =
        await InteractionsClient(getIt<AccountsService>().currentProfile)
            .getLikes(statusId);
    if (likesResult.isSuccess) {
      _likesByStatusId[statusId] = likesResult.value;
      notifyListeners();
    }
    return likesResult;
  }

  FutureResult<List<Connection>, ExecError> updateResharesForStatus(
      String statusId) async {
    final resharesResult =
        await InteractionsClient(getIt<AccountsService>().currentProfile)
            .getReshares(statusId);
    if (resharesResult.isSuccess) {
      _resharesByStatusId[statusId] = resharesResult.value;
      notifyListeners();
    }
    return resharesResult;
  }
}
