import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/feedback_subject_suggestion_type_model.dart';
import 'package:peasmartcare/models/feedback_suggestion_type_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_suggestion_type_event.dart';
part 'feedback_suggestion_type_state.dart';

class FeedbackSuggestionTypeBloc extends Bloc<FeedbackSuggestionTypeEvent, FeedbackSuggestionTypeState> {
  FeedbackImpService service = FeedbackImpService();

  ResultData suggestionTypeResultData;
  ResultData subjectSuggestionTypeResultData;

  FeedbackSuggestionTypeBloc() : super(FeedbackSuggestionTypeInitial());

  @override
  Stream<FeedbackSuggestionTypeState> mapEventToState(FeedbackSuggestionTypeEvent event) async* {
    try {
      if (event is FeedbackSuggestionTypeGetSuggestionTypeList) {
        yield FeedbackSuggestionTypeLoading();

        suggestionTypeResultData = await service.getFeedbackSuggestionTypeList(
          authenKey: ShareDataUtil.getAuthenKey(),
          feedbackTypeId: event.feedbackTypeId,
        );

        if (suggestionTypeResultData.statusCode == 401) {
          yield FeedbackSuggestionTypeErrorUnauthorized();
        } else {
          yield FeedbackSuggestionTypeLoaded(
            resultSuggestionType: suggestionTypeResultData.result,
            resultSubjectSuggestionType: [],
          );
        }
      } else if (event is FeedbackSuggestionTypeGetSubjectSuggestionTypeList) {
        yield FeedbackSuggestionTypeLoading();

        subjectSuggestionTypeResultData = await service.getFeedbackSubjectSuggestionTypeList(
          authenKey: ShareDataUtil.getAuthenKey(),
          suggestionTypeId: event.suggestionTypeId,
        );

        if (suggestionTypeResultData.statusCode == 401) {
          yield FeedbackSuggestionTypeErrorUnauthorized();
        } else {
          yield FeedbackSuggestionTypeLoaded(
            resultSuggestionType: suggestionTypeResultData.result,
            resultSubjectSuggestionType: subjectSuggestionTypeResultData.result,
          );
        }
      }
    } catch (e) {
      yield FeedbackSuggestionTypeError(message: "Error");
    }
  }
}
