import 'package:dio/dio.dart';

import '../../../../core/error/custom_error.dart';
import '../../../../core/network/ws_client.dart';
import '../../../../core/resources/data_state.dart';
import '../../domain/entities/table_entities.dart';
import '../../domain/repository/game_repository.dart';
import '../data_source/remote/game_api_provider.dart';
import '../data_source/remote/game_ws_provider.dart';

class GameRepositoryImpl extends GameRepository {
  final GameWsProvider ws;
  final GameApiProvider api;
  GameRepositoryImpl(this.ws, this.api);

  @override
  Stream<Map<String, dynamic>> get messages => ws.messages;

  @override
  Stream<WsStatus> get status => ws.status;

  @override
  Future<void> connect() => ws.connect();

  @override
  void send(Map<String, dynamic> msg) => ws.send(msg);

  @override
  Future<void> disconnect() => ws.disconnect();

  @override
  Future<DataState<List<TableTier>>> getTiers() async {
    final Response res = await api.getShop();
    if (res.statusCode == 200) {
      final cat = Map<String, dynamic>.from(res.data['catalog'] as Map);
      final list = ((cat['table_tiers'] as List?) ?? [])
          .map((e) => TableTier.fromJson(Map<String, dynamic>.from(e as Map)))
          .toList();
      return DataSuccess(list);
    }
    return DataError(errorConvertor(res.statusCode, null));
  }

  @override
  Future<DataState<TablesInfo>> getTablesInfo() async {
    final Response res = await api.getTablesInfo();
    if (res.statusCode == 200) {
      return DataSuccess(
          TablesInfo.fromJson(Map<String, dynamic>.from(res.data as Map)));
    }
    return DataError(errorConvertor(res.statusCode, null));
  }
}
