
import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/core/services/api/courses_services.dart';
import 'package:hoshan/data/model/courses_model.dart';

part 'courses_event.dart';
part 'courses_state.dart';

class CoursesBloc extends Bloc<CoursesEvent, CoursesState> {
  CoursesBloc() : super(CoursesInitial()) {
    on<CoursesEvent>((event, emit) async {
      if (event is GetAllCourses) {
        emit(CoursesLoading());
        try {
          final courses = <Courses>[];

          final response = await CoursesServices.dio.get(
              CoursesServices.getCourses,
              options: Options(headers: CoursesServices.getAuth()));
          response.data.forEach((v) {
            courses.add(Courses.fromJson(v));
          });
          courses.removeWhere(
            (element) {
              return element.categories
                      ?.any((category) => category.id == 139) ??
                  false;
            },
          );
          emit(CoursesSuccess(courses: courses));
        } on DioException catch (e) {
          emit(CoursesFail());
          if (kDebugMode) {
            print('Dio Error is: $e');
          }
        }
      }
    });
  }
}
