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

// 3. state provider
final googleApisProvider =
    StateNotifierProvider<GoogleApisNotifier, GoogleApisState>(
        (ref) => GoogleApisNotifier(ref: ref));

// 2. notifier
class GoogleApisNotifier extends StateNotifier<GoogleApisState> {
  final Ref ref;
  GoogleApisNotifier({required this.ref}) : super(GoogleApisStateInit());

  void getAddressGoogleApis(
      {required double latitude, required double longitude}) async {
    try {
      state = GoogleApisStateLoading();
      final graphql = ref.read(graphqlProvider(''));
      final dio = ref.read(dioProvider);
      final resp = await GoogleApisRepository(graphql: graphql, dio: dio).getAddressFromCoordinates(
        latitude,
        longitude,
      );

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

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

class GoogleApisStateInit extends GoogleApisState {
  GoogleApisStateInit() : super(DateTime.now());
}

class GoogleApisStateLoading extends GoogleApisState {
  GoogleApisStateLoading() : super(DateTime.now());
}

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

class GoogleApisStateDone extends GoogleApisState {
  final String? model;
  GoogleApisStateDone({
    required this.model,
  }) : super(DateTime.now());
}
