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

part 'create_assistant_event.dart';
part 'create_assistant_state.dart';

class CreateAssistantBloc
    extends Bloc<CreateAssistantEvent, CreateAssistantState> {
  CreateAssistantBloc() : super(CreateAssistantInitial()) {
    on<CreateAssistantEvent>((event, emit) async {
      if (event is CreateAnAssistant) {
        emit(CreateAssistantLoading());
        try {
          if (event.id != null) {
            await BotRepository.editBot(id: event.id!, model: event.model);
          } else {
            await BotRepository.createBot(model: event.model);
          }
          emit(CreateAssistantSuccess(isEdit: event.id != null));
        } on DioException catch (e) {
          emit(const CreateAssistantFail());
          if (kDebugMode) {
            print('Dio Error is: $e');
          }
        }
      }
    });
  }
}
