import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../../networking/restful_api_viewmodel.dart';
import '../../mobile_card/models/product_mobile_card_model.dart';
import '../models/my_product_status_type.dart';

class MyMobileCardListViewModel extends RestfulApiViewModel {
  final RxInt selectedTabIndex = 0.obs;
  var myProducts = <ProductMobileCardModel>[].obs;
  void Function(String message)? onShowAlertError;

  @override
  void onInit() {
    super.onInit();
    freshData(isRefresh: true);
  }

  void selectTab(int index) {
    selectedTabIndex.value = index;
    freshData(isRefresh: true);
  }

  void freshData({bool isRefresh = false}) {
    final body = {
      "index": isRefresh ? 0 : myProducts.length,
      "size": 20,
    };
    final status = selectedTabIndex.value == 0 ? MyProductStatusType.waiting : MyProductStatusType.used;
    client.getMyMobileCards(status, body).then((response) {
      if (!response.isSuccess) {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
      }
      final result = response.data?.listItems ?? [];
      if (isRefresh) {
        myProducts.clear();
      }
      myProducts.addAll(result);
    }).catchError((error) {
      myProducts.clear();
      print('Error fetching products: $error');
    });
  }
}