import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/core/network/api/game_api.dart' deferred as game_api;
import 'package:mypoint_flutter_app/features/game/models/game_bundle_item_model.dart';
import '../../core/network/restful_api_viewmodel.dart';
import 'models/game_bundle_response.dart';

class GameTabViewModel extends RestfulApiViewModel {
  final RxList<GameBundleItemModel> games = <GameBundleItemModel>[].obs;
  final RxString turnsNumberText = "".obs;
  void Function(String message)? onShowAlertError;
  void Function(GameBundleItemModel data)? gotoGameDetail;

  bool _gameApiLoaded = false;

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

  Future<void> getGames() {
    return callApi<GameBundleResponse>(
      request: () async {
        await _ensureGameApiLoaded();
        final api = game_api.GameApi(client);
        return api.getGames();
      },
      onSuccess: (data, _) {
        games.assignAll(data.games ?? []);
        turnsNumberText.value = data.turnsNumberText ?? "";
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  void getGameDetail(String gameId) {
    callApi<GameBundleItemModel>(
      request: () async {
        await _ensureGameApiLoaded();
        final api = game_api.GameApi(client);
        return api.getGameDetail(gameId);
      },
      onSuccess: (data, _) {
        gotoGameDetail?.call(data);
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }
}
