import 'dart:async';

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

part 'feedback_save_event.dart';
part 'feedback_save_state.dart';

class FeedbackSaveBloc extends Bloc<FeedbackSaveEvent, FeedbackSaveState> {
  FeedbackImpService service = FeedbackImpService();

  ResultData resultData;

  FeedbackSaveBloc() : super(FeedbackSaveInitial());

  @override
  Stream<FeedbackSaveState> mapEventToState(FeedbackSaveEvent event) async* {
    try {
      if (event is FeedbackSaveOnSubmit) {
        yield FeedbackSaveLoading();

        UserModel user = ShareDataUtil.getUserInfo();

        resultData = await service.save(
          feedbackTypeId: event.feedbackTypeId,
          name: event.name,
          provinceId: event.provinceId,
          idCard: event.idCard,
          phone: user.phone,
          email: event.email,
          branchId: event.branchId,
          branchName: event.branchName,
          contactLocation: event.contactLocation,
          crimeScene: event.crimeScene,
          suggestionTypeId: event.suggestionTypeId,
          subjectSuggestionTypeId: event.subjectSuggestionTypeId,
          detail: event.detail,
          fileData: event.fileData,
          caNumber: event.caNumber,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield FeedbackSaveErrorUnauthorized();
        } else if (resultData.statusCode == 200) {
          yield FeedbackSaveLoaded(result: resultData.result);
        } else {
          yield FeedbackSaveError(message: "บันทึกไม่สำเร็จ");
        }
      }
    } catch (e) {
      yield FeedbackSaveError(message: "บันทึกไม่สำเร็จ");
    }
  }
}
