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

part 'paymant_history_event.dart';
part 'paymant_history_state.dart';

class PaymantHistoryBloc
    extends Bloc<PaymantHistoryEvent, PaymantHistoryState> {
  PaymantHistoryBloc() : super(PaymantHistoryInitial()) {
    on<PaymantHistoryEvent>((event, emit) async {
      if (event is GetAllHistory) {
        emit(PaymantHistoryLoading());
        try {
          final billings = await PaymantRepository.getPaymantHistory();
          if (billings.isEmpty) {
            emit(PaymantHistoryEmpty());
          } else {
            final List<PaginationBillings> pBillings = [];
            int count = 1;
            for (var i = 0; i < billings.length; i += 5) {
              pBillings.add(PaginationBillings(
                  page: count,
                  billings: billings.sublist(
                      i, i + 5 > billings.length ? billings.length : i + 5)));
              count++;
            }
            emit(PaymantHistorySuccess(billings: pBillings));
          }
        } on DioException catch (e) {
          emit(PaymantHistoryFail());
          if (kDebugMode) {
            print('Dio Error is: $e');
          }
        }
      }
    });
  }
}
