import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/models/otp_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/models/user_model.dart';
import 'package:peasmartcare/services/authen_service.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'login_event.dart';
part 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  AuthenImpService service = AuthenImpService();

  LoginBloc() : super(LoginInitial());

  @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    try {
      if (event is LoginOnSubmit) {
        yield LoginLoading();

        String fullname = event.fullname;
        String idCard = event.idCard;

        ResultData resultData =
            await service.login(fullname: fullname, idCard: idCard);
        print("resLogin2 = ${resultData.result}");
        print("resLogin = ${resultData.statusCode}");
        print("resLogin = ${resultData.statusMessage}");

        if (resultData.statusCode == 200) {
          UserModel user = resultData.result;

          if (user != null) {
            ResultData resultOTPData = await service.sendOTP(
              phoneNumber: user.phone,
              message: "**pw**",
              authenKey: user.authenKey,
            );
            // print("resLogin = ${resultData.statusMessage}");

            if (resultOTPData.result != null) {
              ShareDataUtil.setAuthenKey(user.authenKey);
              ShareDataUtil.setLogin(user.loginStatus);
              ShareDataUtil.setUserInfo(user);

              yield LoginLoaded(
                result: true,
                otpResult: resultOTPData.result,
                phoneNumber: user.phone,
              );
            } else {
              yield LoginLoaded(result: false);
            }
          } else {
            yield LoginLoaded(result: false);
          }
        } else {
          yield LoginError(message: "เข้าสู่ระบบไม่สำเร็จ");
        }
      }
    } catch (e) {
      print("resLogin = ${e}");

      yield LoginError(message: "เกิดข้อผิดพลาด");
    }
  }
}
