import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../provider/dio_provider.dart';
import '../../repository/auth_repository.dart';
import '../../repository/base_repository.dart';

// 3. state provider
final logoutProvider = StateNotifierProvider<LogoutNotifier, LogoutState>(
    (ref) => LogoutNotifier(ref: ref));

// 2. notifier
class LogoutNotifier extends StateNotifier<LogoutState> {
  final Ref ref;
  LogoutNotifier({required this.ref}) : super(LogoutStateInit());
  void logout({
    required String M_UserID,
    required String M_UserUsername,
  }) async {
    try {
      state = LogoutStateLoading();
      final resp = await AuthRepository(dio: ref.read(dioProvider))
          .logout(M_UserID: M_UserID, M_UserUsername: M_UserUsername);

      // print(resp);
      state = LogoutStateDone(message: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = LogoutStateError(message: e.message ?? "");
      } else {
        state = LogoutStateError(message: e.toString());
      }
    }
  }
}

// 1. state
abstract class LogoutState extends Equatable {
  final DateTime date;
  const LogoutState(this.date);
  @override
  List<Object?> get props => [date];
}

class LogoutStateInit extends LogoutState {
  LogoutStateInit() : super(DateTime.now());
}

class LogoutStateLoading extends LogoutState {
  LogoutStateLoading() : super(DateTime.now());
}

class LogoutStateError extends LogoutState {
  final String message;
  LogoutStateError({
    required this.message,
  }) : super(DateTime.now());
}

class LogoutStateDone extends LogoutState {
  final String message;
  LogoutStateDone({
    required this.message,
  }) : super(DateTime.now());
}
