import 'dart:async';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.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 'logout_event.dart';
part 'logout_state.dart';

class LogoutBloc extends Bloc<LogoutEvent, LogoutState> {
  AuthenImpService service = AuthenImpService();
  FirebaseMessaging firebaseMessaging = FirebaseMessaging();

  LogoutBloc() : super(LogoutInitial());

  @override
  Stream<LogoutState> mapEventToState(LogoutEvent event) async* {
    try {
      if (event is LogoutOnPressed) {
        yield LogoutLoading();
        UserModel user = ShareDataUtil.getUserInfo();

        ResultData resultData = await service.logout(
          firstname: user.firstname,
          lastname: user.lastname,
          phone: user.phone,
          idCard: user.idCard,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

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

        ShareDataUtil.clear();
        firebaseMessaging.deleteInstanceID();

        await Future.delayed(Duration(seconds: 1));
        if (resultData.statusCode == 401) {
          yield LogoutErrorUnauthorized();
        } else {
          yield LogoutLoaded(result: true);
        }
      }
    } catch (e) {
      yield LogoutError(message: "เกิดข้อผิดพลาด");
    }
  }
}
