import 'dart:async';

import 'package:fcs/pages/main/model/main_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class OfflineRedirect extends StatefulWidget {
  final Widget child;
  OfflineRedirect({@required this.child});

  @override
  _OfflineRedirectState createState() => _OfflineRedirectState();
}

class _OfflineRedirectState extends State<OfflineRedirect> {
  Timer offlineTimer;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    _startOfflineTimer();
    super.didChangeDependencies();
  }

  _startOfflineTimer() async {
    if (offlineTimer != null && offlineTimer.isActive) return;
    var _duration = new Duration(milliseconds: 500);
    this.offlineTimer = new Timer.periodic(_duration, offlineNav);
  }

  Future<void> offlineNav(Timer timer) async {
    MainModel mainModel = Provider.of<MainModel>(context, listen: false);
    if (!mainModel.isOnline) {
      timer.cancel();
      Navigator.pushNamedAndRemoveUntil(context, "/", (r) => false);
    }
  }

  void dispose() {
    offlineTimer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: widget.child);
  }
}
