import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:flutter_bloc/flutter_bloc.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/firestore_log.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'authen_event.dart';
part 'authen_state.dart';

class AuthenBloc extends Bloc<AuthenEvent, AuthenState> {
  AuthenImpService service = AuthenImpService();

  AuthenBloc() : super(AuthenInitial());

  @override
  Stream<AuthenState> mapEventToState(AuthenEvent event) async* {
    try {
      if (event is AuthenOnDefault) {
        yield AuthenLoading();
        await Future.delayed(Duration(seconds: 2));

        bool isAppBadgeSupported = await FlutterAppBadger.isAppBadgeSupported();
        if (isAppBadgeSupported) {
          FlutterAppBadger.removeBadge();
        }

        bool isLogin = ShareDataUtil.isLogin();
        if (ShareDataUtil.getCustomerId() == null ||
            ShareDataUtil.getCustomerId().isEmpty ||
            ShareDataUtil.getFirebaseToken() == null ||
            ShareDataUtil.getFirebaseToken().isEmpty) {
          isLogin = false;
          ShareDataUtil.setLogin(false);
          ShareDataUtil.clear();
          yield AuthenLoaded(isLogin: isLogin);
        } else if (isLogin) {
          ResultData resultData =
              await service.visitCount(authenKey: ShareDataUtil.getAuthenKey());

          UserModel user = ShareDataUtil.getUserInfo();

          await FirestoreLog.log(
            fullname: "${user.firstname} ${user.lastname}",
            authenKey: ShareDataUtil.getAuthenKey(),
            activity: "On Authen open App",
            caNumber: ShareDataUtil.getCaNumber(),
          );

          if (resultData.statusCode == 401) {
            yield AuthenErrorUnauthorized();
          } else if (resultData.statusCode == 200) {
            yield AuthenLoaded(isLogin: isLogin);
          } else {
            yield AuthenLoaded(isLogin: false);
          }
        }
      }
    } catch (e) {
      UserModel user = ShareDataUtil.getUserInfo();
      await FirestoreLog.log(
        fullname: "${user?.firstname ?? ''} ${user?.lastname ?? ''}",
        authenKey: ShareDataUtil.getAuthenKey(),
        activity: "On Authen catch :: ${e.toString()}",
      );
      yield AuthenError(message: "เกิดข้อผิดพลาด");
      // yield AuthenErrorUnauthorized();
    }
  }
}
