import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'User.dart' as Users;
import 'package:http/http.dart' as http;

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);

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

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  void init() async {
    final prefs = await SharedPreferences.getInstance();
    // http.Response loginResponse = await Users.login('Test1', 'password');
    // print(loginResponse.body);

    if (!prefs.containsKey("password") || !prefs.containsKey("username")) {
      Navigator.of(context).pushNamedAndRemoveUntil('/welcome', (route) => false);
    } else {
      try {
        http.Response loginResponse = await Users.login(
            prefs.getString("username") ?? '',
            prefs.getString("password") ?? '');
        print(loginResponse.body);
        if (loginResponse.body.toLowerCase().contains("success")) {  //Login Success
          Continue();
        } else {                                                      //Login Failed
          LoginFailed();
        }
      } catch (error) {                                               //Login Failed
        LoginFailed();
      }
    }
  }

  void LoginFailed() async{
    bool dbExist = await Users.cacheDbExist();
    if (dbExist) {
      print('cache Database exists, Lets go CACHE!');
      Continue();
    } else {
      Navigator.of(context).pushReplacementNamed('/welcome');
    }
  }

  void Continue() async{
    await Users.initUserData();
    Navigator.of(context).pushNamedAndRemoveUntil('/', (route) => false);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.purple,
        padding: EdgeInsets.all(80),
        child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image(image: AssetImage('images/logo.png')),
              // Text('Loading', style:TextStyle(color: Colors.grey, fontSize: 20,fontStyle: FontStyle.italic))
            ]));
  }
}
