import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/feedback_branch_model.dart';
import 'package:peasmartcare/models/feedback_province_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/services/feedback_service.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'feedback_province_event.dart';
part 'feedback_province_state.dart';

class FeedbackProvinceBloc extends Bloc<FeedbackProvinceEvent, FeedbackProvinceState> {
  FeedbackImpService service = FeedbackImpService();

  ResultData provinceResultData;
  ResultData branchResultData;

  FeedbackProvinceBloc() : super(FeedbackProvinceInitial());

  @override
  Stream<FeedbackProvinceState> mapEventToState(FeedbackProvinceEvent event) async* {
    try {
      if (event is FeedbackProvinceGetProvinceList) {
        yield FeedbackProvinceLoading();

        provinceResultData = await service.getFeedbackProvinceList(
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        yield FeedbackProvinceLoaded(resultProvince: provinceResultData.result, resultBranch: []);
      } else if (event is FeedbackProvinceGetBranchList) {
        yield FeedbackProvinceLoading();

        branchResultData = await service.getFeedbackBranchList(authenKey: ShareDataUtil.getAuthenKey(), provinceId: event.provinceId);

        if (provinceResultData.statusCode == 401) {
          yield FeedbackProvinceErrorUnauthorized();
        } else {
          yield FeedbackProvinceLoaded(resultProvince: provinceResultData.result, resultBranch: branchResultData.result);
        }
      }
    } catch (e) {
      yield FeedbackProvinceError(message: "Error");
    }
  }
}
