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

part 'bots_event.dart';
part 'bots_state.dart';

class BotsBloc extends Bloc<BotsEvent, BotsState> {
  static List<Bots> allBots = [];
  static List<Bots> createBots = [];
  BotsBloc() : super(BotsInitial()) {
    on<BotsEvent>((event, emit) async {
      if (event is GetAllBots) {
        emit(BotsLoading());
        try {
          final response = await BotRepository.getBots();
          final List<Bots> publicBots = [];
          final List<Bots> privateBots = [];
          final List<Bots> toolBots = [];
          if (response.bots != null) {
            createBots.clear();
            allBots.clear();
            allBots.addAll(response.bots!);
            for (var bot in response.bots!) {
              if (bot.public != null) {
                if (bot.tool ?? false) {
                  toolBots.add(bot);
                } else {
                  createBots.add(bot);
                }
                if (bot.public!) {
                  publicBots.add(bot);
                } else {
                  privateBots.add(bot);
                }
              }
            }
          }
          emit(BotsSuccess(
              publicBots: publicBots,
              privateBots: privateBots,
              toolBots: toolBots));
        } on DioException catch (e) {
          emit(BotsFail());
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
    });
  }
}
