import 'dart:async';

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

part 'coordinator_list_event.dart';
part 'coordinator_list_state.dart';

class CoordinatorListBloc extends Bloc<CoordinatorListEvent, CoordinatorListState> {
  CoordinatorImpService service = CoordinatorImpService();

  ResultData resultData;

  CoordinatorListBloc() : super(CoordinatorListInitial());

  @override
  Stream<CoordinatorListState> mapEventToState(CoordinatorListEvent event) async* {
    try {
      if (event is CoordinatorListGetList) {
        yield CoordinatorListLoading();
        resultData = await service.getList(
          customerId: ShareDataUtil.getCustomerId(),
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        List<CoordinatorModel> result = resultData.result;

        if (resultData.statusCode == 401) {
          yield CoordinatorListErrorUnauthorized();
        } else {
          yield CoordinatorListLoaded(result: result, deleteSuccess: null);
        }
      } else if (event is CoordinatorListOnDelete) {
        String id = event.id;
        String authenKey = ShareDataUtil.getAuthenKey();

        yield CoordinatorListLoading();
        ResultData deleteResult = await service.delete(
          id: id,
          authenKey: authenKey,
        );

        if (resultData.statusCode == 401) {
          yield CoordinatorListErrorUnauthorized();
        } else {
          yield CoordinatorListLoaded(result: resultData.result, deleteSuccess: deleteResult.result);
        }
      }
    } catch (e) {
      yield CoordinatorListError(message: "Error");
    }
  }
}
