import 'package:get/get.dart';
import 'package:taafee_mobile/features/card/data_layer/source/card_service.dart';
import 'package:taafee_mobile/features/category/data_layer/model/category.dart';
import 'package:taafee_mobile/features/category/data_layer/source/category_service.dart';
import 'package:rx_future/rx_future.dart';

import '../../../core/utils/pagination_list.dart';
import '../../card/data_layer/model/card_model.dart';

class CategoryController extends GetxController {
  ///-----------data source--------///
  CategoryService categoryService = CategoryService();
  CardService cardService = CardService();
//-------get categories----------//
  RxFuture<List<CategoryModel>> categoryState = RxFuture(<CategoryModel>[]);

  Future<void> getCategories({
    String? value,
    void Function(Object)? onConnectionError,
  }) async {
    await categoryState.observe((p0) async {
      return await categoryService.getCategories(
          value: value, onConnectionError: onConnectionError);
    });
  }

  CategoryModel getCategoryById(int id) {
    for (int i = 0; i < categoryState.result.length; i++) {
      if (id == categoryState.result[i].id) {
        return categoryState.result[i];
      }
    }
    return CategoryModel.zero();
  }

  //-----get category cards------//
  RxFuture<Pagination<CardModel>> categoryCardsState =
      RxFuture(Pagination.zero());

  Future<void> getCategoryCards({
    required int categoryId,
    void Function(Pagination<CardModel>)? onSuccess,
    void Function(Object)? onError,
    void Function(Object)? onConnectionError,
  }) async {
    await categoryCardsState.observe(
      (p0) async {
        await p0!.nextPage((currentPage) async {
          List<CardModel> cards = await cardService.getCards(
            page: currentPage,
            categoryId: categoryId,
            onConnectionError: onConnectionError,
          );
          if (cards.isEmpty) return [];

          return cards;
        });
        return p0;
      },
      onSuccess: onSuccess,
      onError: onError,
    );
  }

  /// -------------- search categories ---------------///
  RxFuture<List<CategoryModel>> searchCategoriesState =
      RxFuture(<CategoryModel>[]);

  Future<void> searchCategories({String? value}) async {
    await searchCategoriesState.observe((p0) async {
      return await categoryService.getCategories(value: value);
    });
  }
}
