import 'package:flutter/widgets.dart';

import 'app_config.dart';
import 'app_services.dart';

/// An [InheritedWidget] that exposes [AppServices] and [AppConfig] to the
/// widget tree.
///
/// Wrap the app (or a subtree) with [AppScope] and retrieve the services
/// anywhere below via [AppScope.of(context)].
class AppScope extends InheritedWidget {
  final AppServices services;
  final AppConfig config;

  const AppScope({super.key, required this.services, required this.config, required super.child});

  /// Returns the nearest [AppServices] from the widget tree.
  ///
  /// Throws if no [AppScope] ancestor is found.
  static AppServices of(BuildContext context) {
    final scope = context.dependOnInheritedWidgetOfExactType<AppScope>();
    assert(scope != null, 'No AppScope found in the widget tree');
    return scope!.services;
  }

  /// Returns the nearest [AppConfig] from the widget tree.
  ///
  /// Throws if no [AppScope] ancestor is found.
  static AppConfig configOf(BuildContext context) {
    final scope = context.dependOnInheritedWidgetOfExactType<AppScope>();
    assert(scope != null, 'No AppScope found in the widget tree');
    return scope!.config;
  }

  @override
  bool updateShouldNotify(AppScope oldWidget) =>
      services != oldWidget.services || config != oldWidget.config;
}
