import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import '../model/lesson_model.dart';
import '../request/lesson_request.dart';

part 'lesson_event.dart';
part 'lesson_state.dart';

class LessonBloc extends Bloc<LessonEvent, LessonState> {
  LessonBloc() : super(const LessonInitial()) {
    on<RequestLesson>((event, emit) async {
      await _requestLesson(event, emit);
    });
  }

  Future<void> _requestLesson(RequestLesson event, Emitter<LessonState> emit) async {
    if (event.lessonID.isEmpty) {
      emit(const LessonFailed('lessonID is Empty!'));
      emit(const LessonResetState());
      return;
    }
    RemoteLesson remoteLesson = RemoteLesson();
    try {
      LessonModel? lessonModel = await remoteLesson.getLessonModel(
        context: event.context,
        lessonID: event.lessonID,
      );
      emit(LessonSuccess(lessonModel!));
    } catch (e) {
      emit(const LessonFailed('request false2!'));
    }
  }

  @override
  Future<void> close() {
    return super.close();
  }

}

