import 'package:get/get.dart';
import 'package:taafee_mobile/features/favorite/data_layer/model/favorite.dart';
import 'package:taafee_mobile/features/favorite/data_layer/source/favorite_service.dart';
import 'package:rx_future/rx_future.dart';

import '../../card/data_layer/model/card_model.dart';

class FavoriteController extends GetxController {
  FavoriteService favoriteService = FavoriteService();

  ///-----------get favorite-----------//
  RxFuture<List<FavoriteModel>> getFavoriteState = RxFuture(<FavoriteModel>[]);

  Future<void> getFavorites({void Function(Object)? onConnectionError}) async {
    await getFavoriteState.observe((p0) async {
      return await favoriteService.getFavorites(
          onConnectionError: onConnectionError);
    });
  }

  bool isCardFav(int id) {
    bool isCardFav = false;
    for (var element in getFavoriteState.result) {
      if (element.cardModel.id == id) {
        isCardFav = true;
        break;
      }
    }
    return isCardFav;
  }

  FavoriteModel? getFavCardById(int id) {
    for (var element in getFavoriteState.value.value) {
      if (element.cardModel.id == id) {
        return element;
      }
    }
    return null;
  }

  void toggleFavoriteCard(int id, {int userId = 0, CardModel? cardModel}) {
    if (isCardFav(id)) {
      FavoriteModel modelToRemove = getFavCardById(id)!;
      getFavoriteState.update((val) {
        val!.value.remove(modelToRemove);
      });
      getFavoriteState.refresh();
    } else {
      getFavoriteState.update((val) {
        val!.value
            .add(FavoriteModel(id: id, userId: userId, cardModel: cardModel!));
      });
      getFavoriteState.refresh();
    }

    // List<FavoriteModel> temp = getFavoriteState.result;
    // for (int i = 0; i < temp.length; i++) {
    //   if (temp[i].cardModel.id == id) {
    //     temp[i].cardModel.isFav = !getFavoriteState.result[i].cardModel.isFav;

    //     break;
    //   }
    // }
    // getFavoriteState.update((val) {
    //   val!.value = temp;
    // });
    // getFavoriteState.refresh();
    // // cardState.result.data.firstWhere((element) => element.id == id).isFav =
    // //     !removeFromFavorite;

    // update();
  }
}
