import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/models/survey_subject_model.dart';
import 'package:peasmartcare/services/survey_service.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'survey_subject_event.dart';
part 'survey_subject_state.dart';

class SurveySubjectBloc extends Bloc<SurveySubjectEvent, SurveySubjectState> {
  SurveyImpService service = SurveyImpService();

  ResultData resultData;

  SurveySubjectBloc() : super(SurveySubjectInitial());

  @override
  Stream<SurveySubjectState> mapEventToState(SurveySubjectEvent event) async* {
    try {
      if (event is SurveySubjectGetData) {
        yield SurveySubjectLoading();

        resultData = await service.getSubject(
          surveyId: event.surveyId,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield SurveySubjectErrorUnauthorized();
        } else {
          yield SurveySubjectLoaded(result: resultData.result);
        }
      }
    } catch (e) {
      yield SurveySubjectError(message: "Error");
    }
  }
}
