import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/ReportsRepository.dart';
import 'package:road24_mobile/data/response/ReportDetailResponse.dart';
import 'package:road24_mobile/data/response/ReportsResponse.dart';

part 'reports_event.dart';

part 'reports_state.dart';

class ReportsBloc extends Bloc<ReportsEvent, ReportsState> {
  final ReportsRepository repository;

  ReportsBloc({required this.repository}) : super(ReportsInitial());

  @override
  Stream<ReportsState> mapEventToState(
    ReportsEvent event,
  ) async* {
    if (event is GetReportsEvent) {
      // try {
      yield ReportsInitial();
      final dynamic response = await repository.getReports(
        pageSize: event.pageSize,
        page: event.page,
      );
      yield GetReportsSuccessState(
        response: ReportsResponse.fromJson(response),
      );
      // } catch (e) {
      //   yield ReportsLoadingError(exception: e);
      // }
    }

    if (event is CreateNewReportsEvent) {
      try {
        yield ReportsInitial();
        final response = await repository.createReport(
          type: event.type,
          number: event.number,
        );
        print(response);
        yield CreateNewReportsSuccessState(
            response: ReportsResponse.fromJson(response));
      } catch (e) {
        yield ReportsLoadingError(exception: e);
      }
    }

    if (event is GetSingleReportDetailEvent) {
      try {
        yield ReportDetailInitial();
        final dynamic response = await repository.reportDetail(event.id);
        yield GetReportDetailSuccessState(
            ReportDetailResponse.fromJson(response.data));
      } catch (e) {
        print(e);
        yield ReportDetailError(exception: e);
      }
    }
  }
}
