import 'package:flutter/material.dart';

import 'internet_change_service.dart';
import 'internet_unconnected_widget.dart';

class InternetChangeCase extends StatefulWidget {
  final Widget child;

  const InternetChangeCase({super.key, required this.child});

  @override
  State<InternetChangeCase> createState() => _InternetChangeCaseState();
}

class _InternetChangeCaseState extends State<InternetChangeCase>
    with StateMixin {
  late final INetworkChangeManager _networkChange;
  NetworkResult? _networkResult;
  @override
  void initState() {
    super.initState();
    _networkChange = NetworkChangeManager();

    waitForScreen(() {
      _networkChange.handleNetworkChange((result) {
        _updateView(result);
      });
    });
  }

  Future<void> fetchFirstResult() async {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final result = await _networkChange.checkNetworkFirstTime();
      _updateView(result);
    });
  }

  void _updateView(NetworkResult result) {
    setState(() {
      _networkResult = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _networkResult == NetworkResult.off
        ? const InternetUnConnectedWidget()
        : widget.child;
  }
}

mixin StateMixin<T extends StatefulWidget> on State<T> {
  void waitForScreen(VoidCallback onComplete) {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      onComplete.call();
    });
  }
}
