import 'dart:async';
import 'package:absenkuv3/Repository/Model/mSplashScreen.dart';
import 'package:absenkuv3/Repository/Service/userApi.dart';
import 'package:absenkuv3/UI/Template/dialog/alertDialog.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sn_progress_dialog/sn_progress_dialog.dart';
import 'CustomFunction.dart';

abstract class ResetPasswordEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

class CekEmailEvent extends ResetPasswordEvent {
  String email;
  CekEmailEvent(BuildContext _context, this.email) {
    context = _context;
  }
}

abstract class ResetPasswordState {}

class CekPasswordTrueState extends ResetPasswordState {
  CekPasswordTrueState(ResetPasswordEvent event, BasicRespon respon) {
    Future.delayed(Duration(milliseconds: 600)).then((value) {
      // BlocProvider.of<NavigatorBloc>(event.context).add(NavigatePop(event.context));
      showDialog(
        barrierDismissible: false,
        context: event.context!,
        builder: (BuildContext dcontext) => AlertDialogCustom(
          data: respon,
          onClick: () {
            Navigator.of(dcontext).pop();
            Navigator.of(event.context!).pop();
          },
        ),
      );
    });
  }
}

class CekPasswordFalseState extends ResetPasswordState {
  String? message;
  CekPasswordFalseState(ResetPasswordEvent event, this.message);
}

class ResetPasswordProgress extends ResetPasswordState {}

class ResetPasswordErrorState extends ResetPasswordState {}

class ResetPasswordBloc extends Bloc<ResetPasswordEvent, ResetPasswordState> {
  ResetPasswordState? initialState;

  ResetPasswordBloc(ResetPasswordState initialState) : super(initialState);

  @override
  Stream<ResetPasswordState> mapEventToState(ResetPasswordEvent event) async* {
    if (event is CekEmailEvent) {
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd);
      BasicRespon basicRespon = await UserApi().resetPassword(event.email);
      ProgressDialogDelayed.hide(pd);
      if (basicRespon.success!)
        yield CekPasswordTrueState(event, basicRespon);
      else
        yield CekPasswordFalseState(event, basicRespon.message);
    }
  }
}
