import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:queuedisplay/model/counter_model.dart';
import 'package:queuedisplay/repository/counter_repository.dart';

import '../repository/base_repository.dart';

import 'dio_provider.dart';

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

class CounterListStateInit extends CounterListState {
  CounterListStateInit() : super(DateTime.now());
}

class CounterListStateLoading extends CounterListState {
  CounterListStateLoading() : super(DateTime.now());
}

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

class CounterListStateDone extends CounterListState {
  final List<Counter> model;
  CounterListStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class CounterListNotifier extends StateNotifier<CounterListState> {
  final Ref ref;
  CounterListNotifier({
    required this.ref,
  }) : super(CounterListStateInit());

  void list() async {
    try {
      state = CounterListStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await CounterRepository(dio: dio).getData();
      state = CounterListStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = CounterListStateError(message: e.message);
      } else {
        state = CounterListStateError(message: e.toString());
      }
    }
  }
}

//provider
final CounterProvider =
    StateNotifierProvider<CounterListNotifier, CounterListState>(
        (ref) => CounterListNotifier(ref: ref));
