import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/api/game_api.dart' deferred as game_api;
import '../../../configs/constants.dart';
import '../../../networking/restful_api_viewmodel.dart';
import '../../../widgets/alert/popup_data_model.dart';
import '../models/game_bundle_item_model.dart';

class GameCardViewModel extends RestfulApiViewModel {
  final Rxn<GameBundleItemModel> data = Rxn<GameBundleItemModel>();
  void Function(String message, bool onClose)? onShowAlertError;
  void Function(PopupDataModel popup)? submitGameCardSuccess;
  void Function()? getGameDetailSuccess;

  bool _gameApiLoaded = false;

  Future<void> _ensureGameApiLoaded() async {
    if (_gameApiLoaded) return;
    await game_api.loadLibrary();
    _gameApiLoaded = true;
  }

  Future<void> submitGameCard(String gameId, int itemId) async {
    await callApi<GameBundleItemModel>(
      request: () async {
        await _ensureGameApiLoaded();
        final api = game_api.GameApi(client);
        return api.submitGameCard(gameId, itemId.toString());
      },
      onSuccess: (data, _) {
        final popupData = data?.popup;
        if (popupData != null) {
          submitGameCardSuccess?.call(popupData);
        } else {
          onShowAlertError?.call(Constants.commonError, false);
        }
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg, false);
      },
    );
  }

  Future<void> getGameDetail({String? id}) async {
    await callApi<GameBundleItemModel>(
      request: () async {
        await _ensureGameApiLoaded();
        final api = game_api.GameApi(client);
        return api.getGameDetail(id ?? data.value?.id ?? '');
      },
      onSuccess: (data, _) {
        this.data.value = data;
        getGameDetailSuccess?.call();
      },
      onFailure: (msg, _, __) async {
        onShowAlertError?.call(msg, true);
      },
    );
  }
}
