import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../configs/constants.dart';
import '../../networking/restful_api_viewmodel.dart';
import 'daily_checkin_models.dart';

class DailyCheckInViewModel extends RestfulApiViewModel {
  var checkInData = Rxn<CheckInDataModel>();
  var submitData = Rxn<SubmitCheckInData>();
  void Function(String message, bool onBack)? onShowAlertError;
  void Function(SubmitCheckInData? data)? submitDataResponse;

  bool get todayIsChecked {
    final counter = checkInData.value?.counters?.first;
    final items = counter?.values ?? [];
    return (items.firstOrNull?.counterValue ?? '') == '1';
  }

  @override
  onInit() {
    super.onInit();
    _rewardOpportunityGetList();
  }

  Future<void> _rewardOpportunityGetList() async {
    showLoading();
    try {
      final response = await client.rewardOpportunityGetList();
      hideLoading();
      checkInData.value = response.data;
      if (!response.isSuccess) {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError, true);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError, true);
    }
  }

  Future<void> submitCheckIn() async {
    showLoading();
    try {
      final response = await client.submitCheckIn();
      hideLoading();
      submitData.value = response.data;
      submitDataResponse?.call(response.data);
      _rewardOpportunityGetList();
      if (!response.isSuccess) {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError, false);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError, false);
    }
  }
}