games_app/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart
2026-09-23 16:28:14 +02:00

1104 lines
41 KiB
Dart

import 'dart:async';
import 'dart:math' as math;
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/realtime/game_socket_service.dart';
import '../../../core/utils/amount_utils.dart';
import '../../../data/models/prediction_models.dart';
import '../../../data/repositories/prediction_repository_impl.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/prediction_repository.dart';
import '../utils/server_adjusted_countdown.dart';
part 'prediction_event.dart';
part 'prediction_state.dart';
/// `Bloc` processes events **concurrently** by default. `PredictionRefreshTick`
/// does an `await`ed HTTP round-trip, so a slow response can resolve *after* a
/// later tick already started/finished — an old, in-flight refresh clobbering
/// state a newer one already updated. Sequential processing (à la
/// `bloc_concurrency`'s `sequential()`, implemented inline to avoid the extra
/// dependency) guarantees ticks are fully handled one at a time, in order.
EventTransformer<E> _sequential<E>() {
return (events, mapper) => events.asyncExpand(mapper);
}
class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
PredictionBloc(this._repo, this._socket, this._walletRepo) : super(const PredictionState.initial()) {
on<PredictionLoadRequested>(_onLoad, transformer: _sequential());
on<PredictionIntervalChanged>(_onIntervalChanged);
on<PredictionStakeSelected>(_onStakeSelected);
on<PredictionDirectionSelected>(_onDirectionSelected);
on<PredictionStakeAccountChanged>(_onStakeAccountChanged);
on<PredictionPlayModeChanged>(_onPlayModeChanged);
on<PredictionMultiLevelSelected>(_onMultiLevelSelected);
on<PredictionMultiDirectionToggled>(_onMultiDirectionToggled);
on<PredictionPlaceBetRequested>(_onPlaceBet);
on<PredictionPlaceMultiBetRequested>(_onPlaceMultiBet);
on<PredictionAutoSaveRequested>(_onAutoSave);
on<PredictionRefreshTick>(_onRefreshTick, transformer: _sequential());
on<PredictionWsMessageReceived>(_onWsMessage);
on<PredictionSocketStatusChanged>(_onSocketStatusChanged);
on<PredictionHistoryPageRequested>(_onHistoryPage);
on<PredictionHistoryFilterChanged>(_onHistoryFilterChanged);
on<PredictionCandlesOlderRequested>(_onOlderCandles);
on<PredictionPaused>(_onPaused);
on<PredictionResumed>(_onResumed);
on<PredictionAppResumed>(_onAppResumed, transformer: _sequential());
on<PredictionBalancesRefreshRequested>(_onBalancesRefresh);
on<PredictionFeedbackConsumed>((event, emit) {
emit(state.copyWith(clearError: true, betPlaced: false));
});
_socket.addListener(_handleSocketMessage);
_socket.addStatusListener(_handleSocketStatus);
}
final PredictionRepository _repo;
final GameSocketService _socket;
final WalletRepositoryImpl _walletRepo;
Timer? _pollTimer;
bool _screenActive = false;
int _multiPollTicks = 0;
int _healthyPollSkips = 0;
int _lastFullStateSyncMs = 0;
static const historyPageSize = 5;
static const _pollJitterRatio = 0.12;
Future<PredictionsPageModel> _fetchHistoryPage(int page) {
return _repo.getMyBets(
page: page,
pageSize: historyPageSize,
intervalMinutes: state.selectedIntervalMinutes,
);
}
bool _matchesHistoryFilters(PredictionModel p) {
if (state.historyWalletFilter != null &&
p.stakeAccountKind != state.historyWalletFilter) {
return false;
}
if (state.historyStatusFilter != null && p.status != state.historyStatusFilter) {
return false;
}
return true;
}
void _handleSocketMessage(Map<String, dynamic> msg) {
if (!_screenActive) return;
add(PredictionWsMessageReceived(msg));
}
void _handleSocketStatus(GameSocketConnectionState status) {
if (!_screenActive) return;
add(PredictionSocketStatusChanged(status));
}
@override
Future<void> close() {
_pollTimer?.cancel();
_socket.removeListener(_handleSocketMessage);
_socket.removeStatusListener(_handleSocketStatus);
return super.close();
}
void _stopPolling() {
_pollTimer?.cancel();
_pollTimer = null;
}
void _startPolling() {
_stopPolling();
if (!_screenActive) return;
final hasActiveMulti = state.gameState?.userMultiBet != null;
final autoOn = state.gameState?.autoSettings?.enabled == true;
// Auto bets are placed server-side without always relying on WS; poll often enough
// to surface pending predictions in Recent predictions quickly.
final Duration interval;
if (autoOn || hasActiveMulti) {
interval = const Duration(seconds: 3);
} else if (_socket.isEnabled && state.isRealtimeHealthy) {
interval = const Duration(seconds: 8);
} else if (_socket.isEnabled) {
interval = const Duration(seconds: 4);
} else {
interval = const Duration(seconds: 2);
}
void scheduleNext() {
if (!_screenActive) return;
final baseMs = interval.inMilliseconds;
final jitterMs = (baseMs * _pollJitterRatio).round();
final offset = jitterMs <= 0
? 0
: math.Random().nextInt(jitterMs * 2 + 1) - jitterMs;
final nextMs = math.max(1000, baseMs + offset);
_pollTimer = Timer(Duration(milliseconds: nextMs), () {
if (!_screenActive) return;
add(const PredictionRefreshTick());
scheduleNext();
});
}
scheduleNext();
}
void _onPaused(PredictionPaused event, Emitter<PredictionState> emit) {
_screenActive = false;
_stopPolling();
_healthyPollSkips = 0;
}
void _onSocketStatusChanged(
PredictionSocketStatusChanged event,
Emitter<PredictionState> emit,
) {
final nextRealtime = switch (event.status) {
GameSocketConnectionState.connected => PredictionRealtimeStatus.live,
GameSocketConnectionState.connecting => PredictionRealtimeStatus.syncing,
GameSocketConnectionState.reconnecting => PredictionRealtimeStatus.reconnecting,
GameSocketConnectionState.stale => PredictionRealtimeStatus.reconnecting,
GameSocketConnectionState.disconnected => PredictionRealtimeStatus.polling,
};
final wasHealthy = state.isRealtimeHealthy;
emit(state.copyWith(
wsConnected: event.status == GameSocketConnectionState.connected,
realtimeStatus: nextRealtime,
));
_startPolling();
if (event.status != GameSocketConnectionState.connected) {
_healthyPollSkips = 0;
}
if (!wasHealthy && event.status == GameSocketConnectionState.connected) {
add(const PredictionRefreshTick(forceGameState: true));
add(const PredictionBalancesRefreshRequested());
add(const PredictionHistoryPageRequested(1));
}
}
Future<void> _onResumed(PredictionResumed event, Emitter<PredictionState> emit) async {
_screenActive = true;
add(const PredictionLoadRequested());
}
/// True root fix for "countdown stuck until I leave and reopen the page":
/// mobile OSes suspend Dart `Timer`s and can silently drop the WebSocket
/// while backgrounded (screen lock, app switcher, incoming call, long time
/// on the page with the screen off) — none of which fires `onDone`, so
/// [GameSocketService.isConnected] keeps reporting healthy. Nothing was
/// listening for the app returning to the foreground, so the zombie
/// connection / disrupted poll schedule silently lingered until the user
/// manually left and reopened the prediction screen (which forces a fresh
/// `_onLoad`). Wiring [PredictionAppResumed] to `AppLifecycleState.resumed`
/// (see `_PredictionScreenState.didChangeAppLifecycleState`) closes that gap
/// without requiring any user action.
Future<void> _onAppResumed(
PredictionAppResumed event,
Emitter<PredictionState> emit,
) async {
if (!_screenActive) return;
if (_socket.isEnabled) {
await _socket.forceReconnect();
}
// Old recursive Timer chain may have been suspended mid-flight; restart
// it fresh instead of trusting whatever was already scheduled.
_startPolling();
add(const PredictionRefreshTick(forceGameState: true));
}
Future<void> _onBalancesRefresh(PredictionBalancesRefreshRequested event, Emitter<PredictionState> emit) async {
final labels = await _loadBalances(state.gameState?.config.walletTypeCode);
emit(state.copyWith(
mainBalanceLabel: labels.mainLabel,
bonusBalanceLabel: labels.bonusLabel,
testBalanceLabel: labels.testLabel,
mainAvailable: labels.main,
bonusAvailable: labels.bonus,
testAvailable: labels.test,
));
}
Future<
({
String mainLabel,
String bonusLabel,
String testLabel,
double main,
double bonus,
double test,
})> _loadBalances(String? walletTypeCode) async {
try {
final balances = await _walletRepo.getBalances();
if (balances.isEmpty) {
return (
mainLabel: '—',
bonusLabel: '—',
testLabel: '—',
main: 0.0,
bonus: 0.0,
test: 0.0,
);
}
final code = walletTypeCode ?? 'USDT_TRC20';
final match = balances.where((b) => b.walletType.code == code);
final b = match.isNotEmpty ? match.first : balances.first;
final symbol = _shortSymbol(b.walletType.code);
final decimals = b.walletType.decimals;
final main = _rawToDouble(b.available, decimals);
final bonus = _rawToDouble(b.bonusAvailable, decimals);
final test = _rawToDouble(b.testAvailable, decimals);
return (
mainLabel: '${rawAmountToHuman(b.available, decimals)} $symbol',
bonusLabel: '${rawAmountToHuman(b.bonusAvailable, decimals)} $symbol',
testLabel: '${rawAmountToHuman(b.testAvailable, decimals)} $symbol',
main: main,
bonus: bonus,
test: test,
);
} catch (_) {
return (
mainLabel: '—',
bonusLabel: '—',
testLabel: '—',
main: 0.0,
bonus: 0.0,
test: 0.0,
);
}
}
double _rawToDouble(String raw, int decimals) {
final human = rawAmountToHuman(raw, decimals);
return double.tryParse(human) ?? 0;
}
static const insufficientBalanceCode = 'insufficient_balance';
String? _insufficientBalanceError() {
// Balances not loaded yet — let the API validate.
if (state.mainBalanceLabel == '—' &&
state.bonusBalanceLabel == '—' &&
state.testBalanceLabel == '—') {
return null;
}
if (state.selectedStake <= state.selectedWalletAvailable) return null;
return '$insufficientBalanceCode:${state.stakeAccountKind.apiValue}';
}
/// Re-emit even when the message text is unchanged (Equatable would skip otherwise).
void _emitError(Emitter<PredictionState> emit, String message) {
if (state.errorMessage == message) {
emit(state.copyWith(clearError: true));
}
emit(state.copyWith(errorMessage: message));
}
String _shortSymbol(String code) {
final upper = code.toUpperCase();
if (upper.startsWith('USDT')) return 'USDT';
if (upper.contains('_')) return upper.split('_').first;
return upper;
}
StakeAccountKind _parseStakeKind(String value) {
switch (value) {
case 'bonus':
return StakeAccountKind.bonus;
case 'test':
return StakeAccountKind.test;
default:
return StakeAccountKind.main;
}
}
Future<void> _onLoad(PredictionLoadRequested event, Emitter<PredictionState> emit) async {
emit(state.copyWith(status: PredictionStatus.loading, clearError: true));
try {
if (_socket.isEnabled) {
await _socket.connect();
}
final interval = state.selectedIntervalMinutes;
final gameState = await _repo.getState(intervalMinutes: interval);
final pageSize = gameState.interval.chartCandleLimit.clamp(20, 200);
final candlesPage = await _repo.getCandlesPage(
intervalMinutes: gameState.selectedIntervalMinutes,
limit: pageSize,
);
final history = await _fetchHistoryPage(1);
final labels = await _loadBalances(gameState.config.walletTypeCode);
if (_socket.isEnabled) {
await _socket.connect();
if (_socket.isConnected) {
_socket.subscribe(gameState.selectedIntervalMinutes);
}
}
final historyItems = gameState.userMultiBet != null
? _historyWithMultiProgress(history.items, gameState.userMultiBet!)
: history.items;
// Prefer wallet of active multi; else auto wallet while enabled; else main.
final auto = gameState.autoSettings;
final multi = gameState.userMultiBet;
final stakeKind = multi != null
? _parseStakeKind(multi.stakeAccountKind)
: (auto?.enabled == true)
? _parseStakeKind(auto!.stakeAccountKind)
: StakeAccountKind.main;
final nextStake = state.status == PredictionStatus.initial
? (auto?.enabled == true && auto!.stakeDisplay > 0
? auto.stakeDisplay
: _defaultStake(gameState.config))
: state.selectedStake;
emit(state.copyWith(
status: PredictionStatus.ready,
gameState: gameState,
candles: candlesPage.items,
hasMoreOlderCandles: candlesPage.hasMore,
isLoadingOlderCandles: false,
history: historyItems,
historyPage: history.page,
historyTotalPages: history.totalPages,
selectedIntervalMinutes: gameState.selectedIntervalMinutes,
selectedStake: nextStake,
multiSequence: _initialMultiSequence(gameState),
selectedMultiLevel: gameState.multiLevels.isNotEmpty
? gameState.multiLevels.first
: state.selectedMultiLevel,
playMode: gameState.userMultiBet != null
? PredictionPlayMode.multi
: (auto?.enabled == true ? PredictionPlayMode.auto : state.playMode),
stakeAccountKind: stakeKind,
mainBalanceLabel: labels.mainLabel,
bonusBalanceLabel: labels.bonusLabel,
testBalanceLabel: labels.testLabel,
mainAvailable: labels.main,
bonusAvailable: labels.bonus,
testAvailable: labels.test,
wsConnected: _socket.isConnected,
realtimeStatus: _socket.isConnected
? PredictionRealtimeStatus.live
: (_socket.isEnabled ? PredictionRealtimeStatus.syncing : PredictionRealtimeStatus.polling),
));
_lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch;
_healthyPollSkips = 0;
await _fillHistoryUntilFilterMatches(emit);
_startPolling();
} catch (e) {
emit(state.copyWith(
status: PredictionStatus.error,
errorMessage: e.toString(),
wsConnected: _socket.isConnected,
realtimeStatus: _socket.isEnabled
? PredictionRealtimeStatus.polling
: PredictionRealtimeStatus.syncing,
));
}
}
Future<void> _onIntervalChanged(PredictionIntervalChanged event, Emitter<PredictionState> emit) async {
final prevInterval = state.selectedIntervalMinutes;
final gs = state.gameState;
emit(state.copyWith(
selectedIntervalMinutes: event.minutes,
candles: const [],
hasMoreOlderCandles: true,
isLoadingOlderCandles: false,
gameState: gs?.copyWith(
selectedIntervalMinutes: event.minutes,
clearRound: true,
clearUserBet: true,
),
));
if (_socket.isEnabled && _socket.isConnected) {
if (prevInterval != event.minutes) {
_socket.unsubscribe(prevInterval);
}
_socket.subscribe(event.minutes);
}
add(const PredictionLoadRequested());
}
void _onStakeSelected(PredictionStakeSelected event, Emitter<PredictionState> emit) {
emit(state.copyWith(selectedStake: event.stake));
}
void _onDirectionSelected(PredictionDirectionSelected event, Emitter<PredictionState> emit) {
emit(state.copyWith(selectedDirection: event.direction));
}
void _onStakeAccountChanged(PredictionStakeAccountChanged event, Emitter<PredictionState> emit) {
emit(state.copyWith(stakeAccountKind: event.kind));
}
void _onPlayModeChanged(PredictionPlayModeChanged event, Emitter<PredictionState> emit) {
emit(state.copyWith(playMode: event.mode));
}
void _onMultiLevelSelected(PredictionMultiLevelSelected event, Emitter<PredictionState> emit) {
final level = event.level;
emit(state.copyWith(
selectedMultiLevel: level,
multiSequence: List.filled(level.candleCount, 'long'),
));
}
void _onMultiDirectionToggled(PredictionMultiDirectionToggled event, Emitter<PredictionState> emit) {
final seq = List<String>.from(state.multiSequence);
if (event.index < 0 || event.index >= seq.length) return;
seq[event.index] = seq[event.index] == 'long' ? 'short' : 'long';
emit(state.copyWith(multiSequence: seq));
}
Future<void> _onPlaceBet(PredictionPlaceBetRequested event, Emitter<PredictionState> emit) async {
final gs = state.gameState;
if (gs == null) return;
final balanceError = _insufficientBalanceError();
if (balanceError != null) {
_emitError(emit, balanceError);
return;
}
emit(state.copyWith(isPlacingBet: true, clearError: true));
try {
await _repo.placeBet(
direction: state.selectedDirection,
stakeAmount: state.selectedStake,
intervalMinutes: gs.selectedIntervalMinutes,
stakeAccountKind: state.stakeAccountKind.apiValue,
);
// Toast only for this user-initiated success — never from WS/poll echoes.
emit(state.copyWith(isPlacingBet: false, betPlaced: true));
add(const PredictionBalancesRefreshRequested());
add(const PredictionLoadRequested());
} catch (e) {
emit(state.copyWith(isPlacingBet: false));
_emitError(emit, e.toString());
}
}
Future<void> _onPlaceMultiBet(PredictionPlaceMultiBetRequested event, Emitter<PredictionState> emit) async {
final gs = state.gameState;
final level = state.selectedMultiLevel;
if (gs == null || level == null) return;
final balanceError = _insufficientBalanceError();
if (balanceError != null) {
_emitError(emit, balanceError);
return;
}
emit(state.copyWith(isPlacingBet: true, clearError: true));
try {
await _repo.placeMultiBet(
level: level.level,
sequence: state.multiSequence,
stakeAmount: state.selectedStake,
intervalMinutes: gs.selectedIntervalMinutes,
stakeAccountKind: state.stakeAccountKind.apiValue,
);
emit(state.copyWith(isPlacingBet: false, betPlaced: true));
add(const PredictionBalancesRefreshRequested());
add(const PredictionLoadRequested());
} catch (e) {
emit(state.copyWith(isPlacingBet: false));
_emitError(emit, e.toString());
}
}
Future<void> _onAutoSave(PredictionAutoSaveRequested event, Emitter<PredictionState> emit) async {
final enabling = event.body['enabled'] == true;
if (enabling) {
final balanceError = _insufficientBalanceError();
if (balanceError != null) {
_emitError(emit, balanceError);
return;
}
}
emit(state.copyWith(isSavingAuto: true, clearError: true));
try {
final saved = await _repo.saveAutoSettings(event.body);
final gs = state.gameState;
if (gs != null) {
emit(state.copyWith(
isSavingAuto: false,
gameState: gs.copyWith(autoSettings: saved),
stakeAccountKind: _parseStakeKind(saved.stakeAccountKind),
selectedStake: saved.stakeDisplay > 0 ? saved.stakeDisplay : state.selectedStake,
playMode: PredictionPlayMode.auto,
clearError: saved.autoBetError == null,
errorMessage: saved.autoBetError,
betPlaced: saved.autoBetPlaced,
));
} else {
emit(state.copyWith(
isSavingAuto: false,
clearError: saved.autoBetError == null,
errorMessage: saved.autoBetError,
betPlaced: saved.autoBetPlaced,
));
}
if (saved.autoBetPlaced) {
add(const PredictionBalancesRefreshRequested());
add(const PredictionLoadRequested());
} else if (saved.enabled) {
_startPolling();
add(const PredictionHistoryPageRequested(1));
}
} catch (e) {
emit(state.copyWith(isSavingAuto: false));
_emitError(emit, e.toString());
}
}
Future<void> _onRefreshTick(PredictionRefreshTick event, Emitter<PredictionState> emit) async {
if (!_screenActive || state.status != PredictionStatus.ready) return;
try {
final interval = state.selectedIntervalMinutes;
final wsOk = _socket.isEnabled && _socket.isConnected;
final hasActiveMulti = state.gameState?.userMultiBet != null;
final autoOn = state.gameState?.autoSettings?.enabled == true;
final prevUserBetId = state.gameState?.userBet?.id;
final prevLastAuto = state.gameState?.autoSettings?.lastAutoBetAt;
final nowMs = DateTime.now().millisecondsSinceEpoch;
final shouldDoSafetyStateSync =
!event.forceGameState &&
wsOk &&
!hasActiveMulti &&
!autoOn &&
(_healthyPollSkips >= 2 || nowMs - _lastFullStateSyncMs >= 20000);
// Skip full state polls only when WS is healthy AND there's nothing that
// needs frequent HTTP sync (auto placement / multi progress / new window).
if (wsOk &&
!hasActiveMulti &&
!autoOn &&
!event.forceGameState &&
!shouldDoSafetyStateSync) {
_healthyPollSkips++;
final labels = await _loadBalances(state.gameState?.config.walletTypeCode);
final gs = state.gameState;
final round = gs?.round;
final nextBet = _userBetForRound(gs?.userBet, round);
emit(state.copyWith(
gameState: gs == null || identical(nextBet, gs.userBet)
? gs
: gs.copyWith(userBet: nextBet, clearUserBet: nextBet == null),
mainBalanceLabel: labels.mainLabel,
bonusBalanceLabel: labels.bonusLabel,
testBalanceLabel: labels.testLabel,
mainAvailable: labels.main,
bonusAvailable: labels.bonus,
testAvailable: labels.test,
wsConnected: true,
realtimeStatus: PredictionRealtimeStatus.live,
));
return;
}
_healthyPollSkips = 0;
final gameState = await _repo.getState(intervalMinutes: interval);
final labels = await _loadBalances(gameState.config.walletTypeCode);
final multi = gameState.userMultiBet;
var history = state.history;
if (multi != null) {
history = _historyWithMultiProgress(history, multi);
}
final userBet = gameState.userBet;
if (userBet != null) {
history = _historyWithPrediction(history, userBet);
}
final userBetChanged = userBet?.id != prevUserBetId;
final autoPlaced =
gameState.autoSettings?.lastAutoBetAt != null &&
gameState.autoSettings?.lastAutoBetAt != prevLastAuto;
emit(state.copyWith(
gameState: _stabilizeGameStateRound(
previous: state.gameState,
incoming: gameState,
forceRound: event.forceGameState,
),
mainBalanceLabel: labels.mainLabel,
bonusBalanceLabel: labels.bonusLabel,
testBalanceLabel: labels.testLabel,
mainAvailable: labels.main,
bonusAvailable: labels.bonus,
testAvailable: labels.test,
wsConnected: _socket.isConnected,
realtimeStatus: _socket.isConnected
? PredictionRealtimeStatus.live
: (_socket.isEnabled ? PredictionRealtimeStatus.reconnecting : PredictionRealtimeStatus.polling),
history: history,
stakeAccountKind: multi != null
? _parseStakeKind(multi.stakeAccountKind)
: state.stakeAccountKind,
));
_lastFullStateSyncMs = nowMs;
if (hasActiveMulti || multi != null || autoOn || userBetChanged || autoPlaced) {
_multiPollTicks++;
if (userBetChanged || autoPlaced || _multiPollTicks % 2 == 0) {
add(const PredictionHistoryPageRequested(1));
}
_startPolling();
} else {
_multiPollTicks = 0;
}
if (_socket.isEnabled && !_socket.isConnected) {
await _socket.connect();
if (_socket.isConnected) {
_socket.subscribe(interval);
_startPolling();
}
}
} catch (_) {}
}
void _onWsMessage(PredictionWsMessageReceived event, Emitter<PredictionState> emit) {
final gs = state.gameState;
if (gs == null) return;
final msg = event.message;
final type = msg['type'] as String?;
final msgInterval = (msg['intervalMinutes'] as num?)?.toInt();
// Ignore realtime events for intervals we are not viewing.
if (msgInterval != null &&
msgInterval != state.selectedIntervalMinutes &&
type != 'connected' &&
type != 'subscribed') {
return;
}
switch (type) {
case 'connected':
emit(state.copyWith(
wsConnected: true,
realtimeStatus: PredictionRealtimeStatus.live,
));
break;
case 'subscribed':
if (msgInterval != null && msgInterval != state.selectedIntervalMinutes) {
return;
}
final snapshot = msg['snapshot'];
if (snapshot is Map<String, dynamic>) {
final next = _stabilizeGameStateRound(
previous: state.gameState,
incoming: GameStateModel.fromJson(snapshot),
);
var history = state.history;
if (next.userMultiBet != null) {
history = _historyWithMultiProgress(history, next.userMultiBet!);
}
if (next.userBet != null) {
history = _historyWithPrediction(history, next.userBet!);
}
emit(state.copyWith(
gameState: next,
selectedIntervalMinutes: next.selectedIntervalMinutes,
wsConnected: true,
realtimeStatus: PredictionRealtimeStatus.live,
history: history,
stakeAccountKind: next.userMultiBet != null
? _parseStakeKind(next.userMultiBet!.stakeAccountKind)
: state.stakeAccountKind,
));
if (next.autoSettings?.enabled == true) {
_startPolling();
}
}
break;
case 'round.updated':
case 'round.settled':
final roundVersions = msg['versions'];
if (roundVersions is Map<String, dynamic>) {
PredictionRepositoryImpl.mergeCachedStateVersions(
state.selectedIntervalMinutes,
round: roundVersions['round'] is num
? (roundVersions['round'] as num).toInt()
: null,
);
}
final round = msg['round'];
if (round is Map<String, dynamic>) {
final parsed = mergeRound(gs.round, RoundModel.fromJson(round));
final prevStatus = gs.round?.status;
final prevRoundId = gs.round?.id;
// Timer-only WS ticks must not remount countdown / overwrite UI state.
if (!roundUiChanged(gs.round, parsed)) {
break;
}
final nextBet = _userBetForRound(gs.userBet, parsed);
emit(state.copyWith(
gameState: gs.copyWith(
round: parsed,
userBet: nextBet,
clearUserBet: nextBet == null,
),
));
// New open window: clear stale lock + sync server state.
final openedBetting = parsed.status == 'betting' && prevStatus != 'betting';
final roundChanged = prevRoundId != null && prevRoundId != parsed.id;
if (openedBetting || (roundChanged && parsed.status == 'betting')) {
add(const PredictionRefreshTick(forceGameState: true));
if (gs.autoSettings?.enabled == true) {
add(const PredictionHistoryPageRequested(1));
}
}
}
if (type == 'round.settled') {
add(const PredictionBalancesRefreshRequested());
add(const PredictionLoadRequested());
}
break;
case 'multi.updated':
final multiVersions = msg['versions'];
if (multiVersions is Map<String, dynamic>) {
PredictionRepositoryImpl.mergeCachedStateVersions(
state.selectedIntervalMinutes,
bet: multiVersions['bet'] is num
? (multiVersions['bet'] as num).toInt()
: null,
);
}
final multi = msg['userMultiBet'];
if (multi is Map<String, dynamic>) {
final parsed = MultiCandlePredictionModel.fromJson(multi);
final history = _historyWithMultiProgress(state.history, parsed);
emit(state.copyWith(
gameState: gs.copyWith(userMultiBet: parsed),
history: history,
playMode: PredictionPlayMode.multi,
stakeAccountKind: _parseStakeKind(parsed.stakeAccountKind),
));
_startPolling();
} else if (multi == null) {
emit(state.copyWith(gameState: gs.copyWith(clearUserMultiBet: true)));
add(const PredictionHistoryPageRequested(1));
_startPolling();
}
break;
case 'candle.append':
final candle = msg['candle'];
if (candle is Map<String, dynamic>) {
final c = OhlcCandleModel.fromJson(candle);
emit(state.copyWith(candles: _mergeCandles(state.candles, [c])));
}
break;
case 'bet.accepted':
final betVersions = msg['versions'];
if (betVersions is Map<String, dynamic>) {
PredictionRepositoryImpl.mergeCachedStateVersions(
state.selectedIntervalMinutes,
bet: betVersions['bet'] is num
? (betVersions['bet'] as num).toInt()
: null,
auto: betVersions['auto'] is num
? (betVersions['auto'] as num).toInt()
: null,
);
}
final betRaw = msg['bet'];
if (betRaw is Map<String, dynamic>) {
final bet = PredictionModel.fromJson(betRaw);
final history = _historyWithPrediction(state.history, bet);
final GameStateModel nextGs;
if (bet.isMulti) {
nextGs = gs.copyWith(
userMultiBet: MultiCandlePredictionModel(
id: bet.id,
level: bet.level ?? bet.sequenceDirections.length,
sequenceDirections: bet.sequenceDirections,
sequenceStep: bet.sequenceStep,
stakeDisplay: bet.stakeDisplay,
status: bet.status,
payoutDisplay: bet.payoutDisplay,
intervalMinutes: bet.intervalMinutes,
stakeAccountKind: bet.stakeAccountKind,
),
clearUserBet: true,
);
} else if (gs.round != null &&
bet.roundId != null &&
bet.roundId!.isNotEmpty &&
bet.roundId != gs.round!.id) {
// Bet is for another round — ignore for the active lock.
nextGs = gs;
} else {
nextGs = gs.copyWith(userBet: bet);
}
final auto = gs.autoSettings;
final nextAuto = (bet.isAuto && auto != null)
? AutoSettingsModel(
enabled: auto.enabled,
direction: auto.direction,
stakeDisplay: auto.stakeDisplay,
mode: auto.mode,
periodMinutes: auto.periodMinutes,
stakeAccountKind: auto.stakeAccountKind,
intervalSeconds: auto.intervalSeconds,
lastAutoBetAt: DateTime.now().toIso8601String(),
autoBetPlaced: false,
autoBetError: null,
)
: auto;
// Update UI/history only — do not toast here (WS echoes / auto rounds /
// other-interval bets caused false "Prediction placed" messages).
emit(state.copyWith(
gameState: nextAuto != null ? nextGs.copyWith(autoSettings: nextAuto) : nextGs,
history: history,
stakeAccountKind: bet.isMulti
? _parseStakeKind(bet.stakeAccountKind)
: state.stakeAccountKind,
));
}
add(const PredictionBalancesRefreshRequested());
add(const PredictionHistoryPageRequested(1));
break;
case 'auto.updated':
final autoVersions = msg['versions'];
if (autoVersions is Map<String, dynamic>) {
PredictionRepositoryImpl.mergeCachedStateVersions(
state.selectedIntervalMinutes,
auto: autoVersions['auto'] is num
? (autoVersions['auto'] as num).toInt()
: null,
);
}
final autoRaw = msg['autoSettings'];
if (autoRaw is Map<String, dynamic>) {
final current = gs.autoSettings;
final merged = AutoSettingsModel(
enabled: autoRaw['enabled'] as bool? ?? current?.enabled ?? false,
direction: autoRaw['direction'] as String? ?? current?.direction,
stakeDisplay: (autoRaw['stakeDisplay'] as num?)?.toDouble() ??
current?.stakeDisplay ??
0,
mode: autoRaw['mode'] as String? ?? current?.mode ?? 'each_round',
periodMinutes: (autoRaw['periodMinutes'] as num?)?.toInt() ??
current?.periodMinutes ??
state.selectedIntervalMinutes,
stakeAccountKind: autoRaw['stakeAccountKind'] as String? ??
current?.stakeAccountKind ??
'main',
intervalSeconds: (autoRaw['intervalSeconds'] as num?)?.toInt() ??
current?.intervalSeconds,
lastAutoBetAt: autoRaw['lastAutoBetAt'] as String? ?? current?.lastAutoBetAt,
autoBetPlaced:
autoRaw['autoBetPlaced'] as bool? ?? current?.autoBetPlaced ?? false,
autoBetError:
autoRaw['autoBetError'] as String? ?? current?.autoBetError,
);
emit(state.copyWith(gameState: gs.copyWith(autoSettings: merged)));
_startPolling();
}
break;
default:
break;
}
}
Future<void> _onHistoryPage(PredictionHistoryPageRequested event, Emitter<PredictionState> emit) async {
emit(state.copyWith(isLoadingHistory: true));
try {
final page = await _fetchHistoryPage(event.page);
final nextHistory = event.append
? [
...state.history,
...page.items.where((item) => state.history.every((h) => h.id != item.id)),
]
: page.items;
final reachedEnd = event.append && page.items.isEmpty;
emit(state.copyWith(
history: nextHistory,
historyPage: reachedEnd ? state.historyPage : page.page,
historyTotalPages: reachedEnd ? state.historyPage : page.totalPages,
isLoadingHistory: false,
));
await _fillHistoryUntilFilterMatches(emit);
} catch (_) {
emit(state.copyWith(isLoadingHistory: false));
}
}
Future<void> _onHistoryFilterChanged(
PredictionHistoryFilterChanged event,
Emitter<PredictionState> emit,
) async {
emit(state.copyWith(
historyWalletFilter: event.walletFilter,
historyStatusFilter: event.statusFilter,
clearHistoryWalletFilter: event.walletFilter == null,
clearHistoryStatusFilter: event.statusFilter == null,
));
await _fillHistoryUntilFilterMatches(emit);
}
/// When a filter is active and the loaded pages have no matches, keep loading
/// older pages until a match appears or the history is fully loaded.
Future<void> _fillHistoryUntilFilterMatches(Emitter<PredictionState> emit) async {
final hasFilter =
state.historyWalletFilter != null || state.historyStatusFilter != null;
if (!hasFilter) return;
var guard = 0;
while (guard < 50) {
guard++;
if (state.history.any(_matchesHistoryFilters)) return;
if (state.historyPage >= state.historyTotalPages) return;
emit(state.copyWith(isLoadingHistory: true));
try {
final page = await _fetchHistoryPage(state.historyPage + 1);
final nextHistory = [
...state.history,
...page.items.where((item) => state.history.every((h) => h.id != item.id)),
];
final reachedEnd = page.items.isEmpty;
emit(state.copyWith(
history: nextHistory,
historyPage: reachedEnd ? state.historyPage : page.page,
historyTotalPages: reachedEnd ? state.historyPage : page.totalPages,
isLoadingHistory: false,
));
if (reachedEnd) return;
} catch (_) {
emit(state.copyWith(isLoadingHistory: false));
return;
}
}
}
Future<void> _onOlderCandles(PredictionCandlesOlderRequested event, Emitter<PredictionState> emit) async {
if (state.candles.isEmpty ||
state.isLoadingOlderCandles ||
!state.hasMoreOlderCandles) {
return;
}
emit(state.copyWith(isLoadingOlderCandles: true));
try {
final oldest = state.candles.first;
final pageSize = (state.gameState?.interval.chartCandleLimit ?? 80).clamp(20, 200);
final page = await _repo.getCandlesPage(
intervalMinutes: state.selectedIntervalMinutes,
beforeOpenMs: oldest.openMs,
limit: pageSize,
);
emit(state.copyWith(
candles: _mergeCandles(page.items, state.candles),
hasMoreOlderCandles: page.hasMore,
isLoadingOlderCandles: false,
));
} catch (_) {
emit(state.copyWith(isLoadingOlderCandles: false));
}
}
static PredictionModel? _userBetForRound(PredictionModel? bet, RoundModel? round) {
if (bet == null || round == null) return null;
return bet.belongsToRound(round) ? bet : null;
}
static List<OhlcCandleModel> _mergeCandles(
List<OhlcCandleModel> a,
List<OhlcCandleModel> b,
) {
if (a.isEmpty) return List<OhlcCandleModel>.from(b);
if (b.isEmpty) return List<OhlcCandleModel>.from(a);
final map = <int, OhlcCandleModel>{};
for (final c in a) {
map[c.openMs] = c;
}
for (final c in b) {
map[c.openMs] = c;
}
final merged = map.values.toList()
..sort((x, y) => x.openMs.compareTo(y.openMs));
return merged;
}
double _defaultStake(PredictConfigModel config) {
if (config.stakeAmounts.isNotEmpty) return config.stakeAmounts.first;
return config.minStakeAmount;
}
/// Keep countdown stable: merge absolute deadlines and ignore timer-only round ticks.
GameStateModel _stabilizeGameStateRound({
required GameStateModel? previous,
required GameStateModel incoming,
bool forceRound = false,
}) {
final incomingRound = incoming.round;
if (incomingRound == null) return incoming;
final merged = mergeRound(previous?.round, incomingRound);
if (!forceRound &&
previous?.round != null &&
!roundUiChanged(previous!.round, merged)) {
return incoming.copyWith(round: previous.round);
}
return incoming.copyWith(round: merged);
}
List<String> _initialMultiSequence(GameStateModel gs) {
final level = gs.multiLevels.isNotEmpty ? gs.multiLevels.first : null;
if (level == null) return const ['long', 'long'];
return List.filled(level.candleCount, 'long');
}
/// Patch history rows with live multi-candle step/status so the list updates
/// without waiting for a full HTTP history reload.
List<PredictionModel> _historyWithMultiProgress(
List<PredictionModel> history,
MultiCandlePredictionModel multi,
) {
var found = false;
final updated = history.map((p) {
if (p.id != multi.id) return p;
found = true;
return PredictionModel(
id: multi.id,
direction: multi.sequenceDirections.isNotEmpty
? multi.sequenceDirections.first
: p.direction,
stakeDisplay: multi.stakeDisplay,
status: multi.status,
payoutDisplay: multi.payoutDisplay,
createdAt: p.createdAt,
stakeAccountKind: p.stakeAccountKind,
isAuto: p.isAuto,
predictionMode: 'multi_candle',
level: multi.level,
sequenceDirections: multi.sequenceDirections,
sequenceStep: multi.sequenceStep,
intervalMinutes: multi.intervalMinutes,
);
}).toList();
if (found) return updated;
final live = PredictionModel(
id: multi.id,
direction: multi.sequenceDirections.isNotEmpty
? multi.sequenceDirections.first
: 'long',
stakeDisplay: multi.stakeDisplay,
status: multi.status,
payoutDisplay: multi.payoutDisplay,
createdAt: DateTime.now().toIso8601String(),
stakeAccountKind: multi.stakeAccountKind,
predictionMode: 'multi_candle',
level: multi.level,
sequenceDirections: multi.sequenceDirections,
sequenceStep: multi.sequenceStep,
intervalMinutes: multi.intervalMinutes,
);
if (!_matchesHistoryFilters(live)) return history;
return [live, ...history];
}
/// Ensure a single/auto prediction appears at the top of Recent predictions.
List<PredictionModel> _historyWithPrediction(
List<PredictionModel> history,
PredictionModel bet,
) {
if (!_matchesHistoryFilters(bet)) return history;
final without = history.where((p) => p.id != bet.id).toList();
return [bet, ...without];
}
}