import 'dart:async';

import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  final log = Logger('_SplashScreenState');
  String page = "/language_selection";
  bool _loaded = false;
  bool _isSupport = false;
  bool _isOnline = true;
  Timer timer;

  startTime() async {
    var _duration = new Duration(milliseconds: 3000);
    this.timer = new Timer.periodic(_duration, navigationPage);
  }

  void navigationPage(Timer timer) async {
    if (_loaded && _isOnline && _isSupport) {
      timer.cancel();
      Navigator.of(context).pushReplacementNamed(page);
    }
  }

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

  void dispose() {
    super.dispose();
    if (timer.isActive) timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    MainModel mainModel = Provider.of<MainModel>(context);

    this._isSupport = mainModel.isSupport();
    this._isOnline = mainModel.isOnline;
    if (mainModel.isLoaded) {
      if (mainModel.isFirstLaunch) {
        page = "/language_selection";
      } else if (mainModel.isLogin()) {
        page = "/home";
      } else {
        page = "/welcome";
      }
      this._loaded = mainModel.isLoaded;
    }

    return new Scaffold(
      backgroundColor: Colors.white,
      body: new Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 180,
              width: 180,
              child: new Image.asset(
                "assets/logo.jpg",
              ),
            ),
            SizedBox(height: 50),
            Column(
              children: <Widget>[
                Text(
                  "FCS Logistics",
                  style: welcomeSubLabelStyle,
                ),
              ],
            ),
            SizedBox(height: 30),
            _loaded && !_isOnline
                ? Column(
                    children: <Widget>[
                      LocalText(context, "offline.status"),
                    ],
                  )
                : Container(),
            Text(
                _loaded && !_isSupport
                    ? "Version outdated, please update your app!"
                    : "",
                style: TextStyle(
                    color: primaryColor, fontWeight: FontWeight.bold)),
          ],
        ),
      ),
    );
  }
}
