import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/data/model/ai/bots_model.dart';
import 'package:hoshan/data/model/tools_categories_model.dart';
import 'package:hoshan/data/repository/bot_repository.dart';

part 'best_assistants_state.dart';

class BestAssistantsCubit extends Cubit<BestAssistantsState> {
  BestAssistantsCubit() : super(BestAssistantsInitial());

  void getAssistants() async {
    emit(BestAssistantsLoading());
    try {
      final cats = await BotRepository.getGlobalAssistant();
      final List<Bots> allBots = cats.categories!.expand((e) {
        return e.bots!.take(2).map(
          (b) {
            return b.copyWith(
                category: Categories(name: e.categoryName, id: b.category?.id));
          },
        ).toList();
      }).toList();
      allBots.sort((a, b) => (b.messages ?? 0).compareTo(a.messages ?? 0));
      emit(BestAssistantsSuccess(
        assistants: allBots,
      ));
    } on DioException catch (e) {
      emit(BestAssistantsFail());
      if (kDebugMode) {
        print('Dio Error is: $e');
      }
    }
  }
}
