part of "./side_nav.dart";

class _NavView extends StatefulWidget {
  /// 导航Id
  final int? navId;

  /// 菜单项集合
  final List<VSideNavMenuItem> items;

  final VSideNavViewController controller;

  const _NavView({
    this.navId,
    required this.items,
    required this.controller,
  });

  @override
  State<StatefulWidget> createState() => _NavViewState();
}

class NavigatorObserverS extends NavigatorObserver {}

class _NavViewState extends State<_NavView> {
  late final WidgetBuilder _bodyBuilder;
  WidgetBuilder? _currentPageBuilder;

  @override
  void initState() {
    if (widget.navId != null) {
      _bodyBuilder = _buildNavigator;
    } else {
      _bodyBuilder = _buildPageBody;
      widget.controller.pageChangedEvent.addListener(_onPageChanged);
    }
    super.initState();
  }

  @override
  void dispose() {
    widget.controller.pageChangedEvent.removeListener(_onPageChanged);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: _bodyBuilder.call(context),
    );
  }

  Widget _buildPageBody(BuildContext context) {
    return _currentPageBuilder?.call(context) ?? const SizedBox();
  }

  Widget _buildNavigator(BuildContext context) {
    return Navigator(
      key: Get.nestedKey(widget.navId),
      initialRoute: widget.controller.currentTitle,
      onGenerateRoute: onGenerateRoute,
    );
  }

  void _onPageChanged(_, WidgetBuilder? e) {
    _currentPageBuilder = e;
    setState(() {});
  }

  /// 路由生成器
  Route? onGenerateRoute(RouteSettings settings) {
    String? name = settings.name;
    if (name == null) return null;

    final item = widget.items.firstWhereOrNull((e) => e.title == name);
    if (item == null) return null;

    final route = item.route!;

    widget.controller.titleChangedEvent.emit(this, item.title);

    return GetPageRoute(
      page: route.page,
      binding: route.binding,
      customTransition: FTransitions.sharedAxisHorizontal,
      transitionDuration: GlobalStyles.navTransitionDuration,
    );
  }
}
