import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../configs/constants.dart';
import 'models/campaign_7day_info_model.dart';
import 'models/campaign_7day_mission_model.dart';
import 'models/campaign_7day_reward_model.dart';

class Campaign7DayViewModel extends RestfulApiViewModel {
  final String campaignId;
  final RxList<String> liveTransactions = <String>[].obs;
  final Rxn<Campaign7DayInfoModel> campaign7DayInfo = Rxn<Campaign7DayInfoModel>();

  void Function(String message, bool onBack)? onShowAlertError;
  void Function(Campaign7DayMissionModel mission)? submitPerformMissionResponse;
  void Function(List<Campaign7DayRewardModel> rewards)? getCampaignRewardsResponse;

  Campaign7DayViewModel({required this.campaignId});

  void getLiveTransactions() {
    callApi<List<String>>(
      request: () => client.getCampaignLiveTransactions(campaignId),
      onSuccess: (data, _) {
        liveTransactions.assignAll(data);
      },
      withLoading: false,
    );
  }

  void getCampaignRewards() {
    callApi<List<Campaign7DayRewardModel>>(
      request: () => client.getCampaignRewards(campaignId),
      onSuccess: (data, _) {
        if (data.isEmpty) {
          onShowAlertError?.call("Bạn chưa có phần thưởng nào. Vui lòng hoàn thành các nhiệm vụ để nhận thưởng!", false);
        } else {
          getCampaignRewardsResponse?.call(data);
        }
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg.isNotEmpty ? msg : Constants.commonError, false);
      },
    );
  }

  void getCampaign7DayInfo({bool silent = false}) {
    callApi<Campaign7DayInfoModel>(
      request: () => client.getCampaignMissions(campaignId),
      onSuccess: (data, _) {
        campaign7DayInfo.value = data;
      },
      onFailure: (msg, _, _) async {
        if (!silent) onShowAlertError?.call(msg.isNotEmpty ? msg : Constants.commonError, true);
      },
    );
  }

  void submitPerformMission(Campaign7DayMissionModel mission) {
    if (!mission.isReady) return;
    callApi<void>(
      request: () => client.submitPerformMission(mission, campaignId),
      onSuccess: (_, __) {
        getCampaign7DayInfo(silent: true);
        if (mission.popup != null) {
          submitPerformMissionResponse?.call(mission);
        } else {
          mission.directionScreen?.begin();
        }
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg.isNotEmpty ? msg : Constants.commonError, false);
      },
    );
  }
}
