import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/history_bill_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/services/history_bill_service.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'history_bill_list_event.dart';
part 'history_bill_list_state.dart';

class HistoryBillListBloc extends Bloc<HistoryBillListEvent, HistoryBillListState> {
  HistoryBillImpService service = HistoryBillImpService();

  ResultData resultData;

  List<HistoryBillModel> historyBillList;

  HistoryBillListBloc() : super(HistoryBillListInitial());

  @override
  Stream<HistoryBillListState> mapEventToState(HistoryBillListEvent event) async* {
    try {
      if (event is HistoryBillListGetList) {
        yield HistoryBillListLoading();
        DateTime currentDate = DateTime.now();
        String caNumber = ShareDataUtil.getCaNumber();
        String yearPayment = (currentDate.year + 543).toString();
        String monthPayment = currentDate.month.toString();

        resultData = await service.getList(
          authenKey: ShareDataUtil.getAuthenKey(),
          caNumber: caNumber,
          yearPayment: yearPayment,
          monthPayment: monthPayment,
        );

        List<HistoryBillModel> historyBillList = resultData.result;

        if (resultData.statusCode == 401) {
          yield HistoryBillListErrorUnauthorized();
        } else {
          yield HistoryBillListLoaded(result: historyBillList);
        }
      }
    } catch (e) {
      yield HistoryBillListError(message: "Error");
    }
  }
}
