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/global_assistant_bots_model.dart';
import 'package:hoshan/data/repository/bot_repository.dart';

part 'global_assistants_event.dart';
part 'global_assistants_state.dart';

class GlobalAssistantsBloc
    extends Bloc<GlobalAssistantsEvent, GlobalAssistantsState> {
  GlobalAssistantsBloc() : super(GlobalAssistantsInitial()) {
    on<GlobalAssistantsEvent>((event, emit) async {
      if (event is GetGlobalAssistants) {
        emit(GlobalAssistantsLoading());
        try {
          final mark = event.category == -2;
          final catId = event.category == -1 || event.category == -2
              ? null
              : event.category;
          final cats = await BotRepository.getGlobalAssistant(
              marked: mark, categorieId: catId);
          emit(GlobalAssistantsSuccess(
              assistants: cats.categories!, category: event.category));
        } on DioException catch (e) {
          emit(GlobalAssistantsFail());
          if (kDebugMode) {
            print('Dio Error is: $e');
          }
        }
      }

      if (event is ChangeGlobalAssistantBot) {
        final updatedList = List.of(state.assistants);
        final index =
            updatedList[event.oldAssistantsIndex].bots!.indexOf(event.oldBot);
        updatedList[event.oldAssistantsIndex].bots![index] = event.newBot;
        emit(GlobalAssistantsSuccess(
            category: state.category, assistants: updatedList));
      }

      // if (event is RemoveGlobalAssistantBot) {
      //   try {
      //     final updatedList = List.of(state.assistants);
      //     final index =
      //         updatedList[event.oldAssistantsIndex].bots!.indexOf(event.oldBot);
      //     updatedList[event.oldAssistantsIndex].bots!.removeAt(index);
      //     emit(GlobalAssistantsSuccess(
      //         category: state.category, assistants: updatedList));
      //   } catch (e) {
      //     if (kDebugMode) {
      //       print(' Error is: $e');
      //     }
      //   }
      // }
    });
  }
}
