import 'dart:async';

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

part 'survey_list_event.dart';
part 'survey_list_state.dart';

class SurveyListBloc extends Bloc<SurveyListEvent, SurveyListState> {
  SurveyImpService service = SurveyImpService();

  ResultData resultData;
  String surveyId;

  SurveyListBloc() : super(SurveyListInitial());

  @override
  Stream<SurveyListState> mapEventToState(SurveyListEvent event) async* {
    try {
      if (event is SurveyListGetList) {
        yield SurveyListLoading();

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

        if (resultData.statusCode == 401) {
          yield SurveyListErrorUnauthorized();
        } else {
          yield SurveyListLoaded(result: resultData.result, deleteSuccess: null);
        }
      } else if (event is SurveyListOnDelete) {
        yield SurveyListLoading();
        String srcqId = event.srcqId;
        ResultData resultDelete = await service.deleteAnswer(srcqId: srcqId, authenKey: ShareDataUtil.getAuthenKey());

        if (resultData.statusCode == 401) {
          yield SurveyListErrorUnauthorized();
        } else {
          yield SurveyListLoaded(result: resultData.result, deleteSuccess: resultDelete.result);
        }
      } else if (event is SurveyListAddSurveyId) {
        surveyId = event.surveyId;

        resultData = await service.getList(
          surveyId: surveyId,
          authenKey: ShareDataUtil.getAuthenKey(),
        );
      }
    } catch (e) {
      yield SurveyListError(message: "Error");
    }
  }
}
