import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
import 'package:peasmartcare/models/otp_model.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 'resend_otp_event.dart';
part 'resend_otp_state.dart';

class ResendOtpBloc extends Bloc<ResendOtpEvent, ResendOtpState> {
  AuthenImpService service = AuthenImpService();
  String _phoneNumber;

  ResendOtpBloc() : super(ResendOtpInitial());

  @override
  Stream<ResendOtpState> mapEventToState(ResendOtpEvent event) async* {
    try {
      if (event is ResendOtpOnSubmit) {
        yield ResendOtpLoading();

        ResultData resultData = await service.sendOTP(
          phoneNumber: _phoneNumber,
          message: "**pw**",
          authenKey: ShareDataUtil.getAuthenKey(),
        );
        print("checkOtp ${resultData.statusCode}");
        print("checkOtp ${resultData.statusMessage}");
        print("checkOtp ${resultData.result}");

        await Future.delayed(Duration(seconds: 2));

        if (resultData.statusCode == 401) {
          yield ResendOtpErrorUnauthorized();
        } else {
          if (resultData.result != null) {
            print("checkOtp ${resultData.result}");

            yield ResendOtpLoaded(result: true, otpResult: resultData.result);
          } else {
            yield ResendOtpLoaded(result: false);
          }
        }
      } else if (event is ResendOtpAddPhone) {
        _phoneNumber = event.phoneNumber;
      }
    } catch (e) {
      print("check catch ${e}");
      yield ResendOtpError(message: "เกิดข้อผิดพลาด");
    }
  }
}
