import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tasktracker/Data.dart';
import 'User.dart' as Users;
import 'package:http/http.dart' as http;
import 'theme_provider.dart';
import 'package:provider/provider.dart';
import 'newActivity.dart';
import 'NotificationsManager.dart';

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

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

class _SplashScreenState extends State<SplashScreen> {
  Future<void> initSettings() async{
    final prefs = await SharedPreferences.getInstance();
    bool value = true;
    if(prefs.containsKey("theme")){
      value = ((await prefs.getInt("theme"))==0);
    }else{
      await prefs.setInt("theme", 0);
    }
    print('Dark theme is : $value');
    final provider = Provider.of<ThemeProvider>(context, listen: false);
    provider.toggleTheme(value);
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
    NotificationManager.RescheduleNotifications();
  }


  void notificationSelected(String? payload) {
    if(payload!=null){
      if(payload.toLowerCase().contains("activity")){
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewActivity())).then((value) => {Users.refreshUserData()});
      }
    }
  }
  void init() async {
    await initSettings();
    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).pushReplacementNamed('/home');
    print('Going home!');
  }

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

  
}
