import 'dart:async';

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

part 'verify_otp_event.dart';
part 'verify_otp_state.dart';

class VerifyOtpBloc extends Bloc<VerifyOtpEvent, VerifyOtpState> {
  AuthenImpService service = AuthenImpService();

  VerifyOtpBloc() : super(VerifyOtpInitial());

  @override
  Stream<VerifyOtpState> mapEventToState(VerifyOtpEvent event) async* {
    try {
      if (event is VerifyOtpOnSubmit) {
        yield VerifyOtpLoading();
        String otpId = event.otpId;
        String otp = event.otp;
        print("otpId = ${otpId}");
        print("otp = ${otp}");

        ResultData resultData = await service.verifyOTP(
          otpId: otpId,
          otp: otp,
          authenKey: ShareDataUtil.getAuthenKey(),
        );
        print("statusCode  ${resultData.statusCode}");
        print("statusMessage  ${resultData.statusMessage}");

        if (resultData.statusCode == 401) {
          yield VerifyOtpErrorUnauthorized();
        } else {
          // ResultData resultVisitCountData =
          //     await service.visitCount(authenKey: ShareDataUtil.getAuthenKey());

          // if (resultData.statusCode == 401) {
          //   yield VerifyOtpErrorUnauthorized();
          // } else if (resultData.statusCode == 200) {
          print("xxx");
          await ShareDataUtil.setNewRegister(true);
          yield VerifyOtpLoaded(result: true);

          // } else {
          //   yield VerifyOtpError(message: "เกิดข้อผิดพลาด");
          // }
        }
      }
    } catch (e) {
      print("catchVerify ${e}");
      yield VerifyOtpError(message: "เกิดข้อผิดพลาด");
    }
  }
}
