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

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

class ReqCabangStateInit extends ReqCabangState {
  ReqCabangStateInit() : super(DateTime.now());
}

class ReqCabangStateLoading extends ReqCabangState {
  ReqCabangStateLoading() : super(DateTime.now());
}

class ReqCabangStateError extends ReqCabangState {
  final String? message;
  ReqCabangStateError({
    required this.message,
  }) : super(DateTime.now());
}

class ReqCabangStateDone extends ReqCabangState {
  final String model;
  ReqCabangStateDone({
    required this.model,
  }) : super(DateTime.now());
}

class ReqCabangNotifier extends StateNotifier<ReqCabangState> {
  final Ref ref;
  ReqCabangNotifier({
    required this.ref,
  }) : super(ReqCabangStateInit());

  void requestTokenCabang({
    required String token,
    required String userID,
    required String username,
    required String targetUrl
  }) async {
    try {
      state = ReqCabangStateLoading();
      final resp = await AliasesRepository(dio: ref.read(dioProvider)).requestToken(token: token, userID: userID, username: username, targetUrl: targetUrl);
      state = ReqCabangStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = ReqCabangStateError(message: e.message ?? "");
      } else {
        state = ReqCabangStateError(message: e.toString());
      }
    }
  }
}

final reqCabangTokenProvider = StateNotifierProvider<ReqCabangNotifier, ReqCabangState>((ref) => ReqCabangNotifier(ref: ref));