import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ticket_booth/model/layanan.dart';
import 'package:ticket_booth/provider/dio_provider.dart';
import 'package:ticket_booth/repository/base_repository.dart';
import 'package:ticket_booth/repository/service_repository.dart';

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

class ServiceListStateInit extends ServiceListState {
  ServiceListStateInit() : super(DateTime.now());
}

class ServiceListStateLoading extends ServiceListState {
  ServiceListStateLoading() : super(DateTime.now());
}

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

class ServiceListStateDone extends ServiceListState {
  final List<Layanan> model;
  ServiceListStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class ServiceListNotifier extends StateNotifier<ServiceListState> {
  final Ref ref;
  ServiceListNotifier({
    required this.ref,
  }) : super(ServiceListStateInit());

  void list({required hostIp}) async {
    try {
      state = ServiceListStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await ServiceRepository(dio: dio).getData(hostIp: hostIp);
      state = ServiceListStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = ServiceListStateError(message: e.message);
      } else {
        state = ServiceListStateError(message: e.toString());
      }
    }
  }
}

//provider
final ServiceListProvider =
    StateNotifierProvider<ServiceListNotifier, ServiceListState>(
        (ref) => ServiceListNotifier(ref: ref));
