import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:quickquiz/apidata/apidata.dart';
import 'package:quickquiz/global.dart';
import 'package:quickquiz/main.dart';
import 'package:quickquiz/pages/home.dart';
import 'package:quickquiz/pages/networkerror_beforelogin.dart';
import 'package:path_provider/path_provider.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();

    getApplicationDocumentsDirectory().then((Directory directory) {
      dir = directory;
      jsonFile = new File(dir.path + "/" + fileName);
      fileExists = jsonFile.existsSync();
      if (fileExists)
        this.setState(
            () => fileContent = json.decode(jsonFile.readAsStringSync()));
    });

    Timer(Duration(seconds: 2), () {
      loginFromFIle();
    });
  }

  void deleteFile() {
    print("Deleting file!");
    File file = File(dir.path + "/" + fileName);
    file.delete();
    setState(() {
      fileExists = false;
    });
  }

  Future<String?> loginFromFIle() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        if (fileExists) {
          print(fileContent);
          final accessToken =
              await http.post(Uri.parse(APIData.tokenApi), headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
          }, body: {
            "email": fileContent!['user'],
            "password": fileContent!['pass'],
          });
          if (accessToken.statusCode != 200) {
            deleteFile();
            var router = new MaterialPageRoute(
                builder: (BuildContext context) => new Home());
            Navigator.of(context).push(router);
          }
          print(accessToken.body);
          var user = json.decode(accessToken.body);
          final response = await http.get(Uri.parse(APIData.quizCatApi),
              // ignore: deprecated_member_use
              headers: {
                // ignore: deprecated_member_use
                HttpHeaders.authorizationHeader:
                    "Bearer ${user['response']['token']}"
              });

          setState(() {
            fullData = "Bearer ${user['response']['token']}";
          });

          dataUser = json.decode(response.body);
          userDetail = dataUser['users'];
          print("user details${userDetail.toString()}");
          userRole = userDetail['role'];
          userId = userDetail['id'];
          userName = userDetail['name'];
          userEmail = userDetail['email'];
          userMobile = userDetail['mobile'];
          userAddress = userDetail['address'];
          userCity = userDetail['city'];
          topicsData = dataUser['topics'];
          qData = dataUser['questions'];
          print(userDetail);
          setState(() {
            name = userName;
            nameInitial = userName[0];
            email = userEmail;
            if (userRole == 'A') {
              role = "Admin";
            } else {
              role = "Student";
            }
            if (userMobile == null) {
              mobile = "N/A";
            } else {
              mobile = userMobile;
            }
            if (userAddress == null) {
              address = "N/A";
            } else {
              address = userAddress;
            }
            if (userCity == null) {
              city = "N/A";
            } else {
              city = userCity;
            }
          });
          var router = new MaterialPageRoute(
              builder: (BuildContext context) => new QuizHome(
                    name: name,
                    email: email,
                    nameInitial: nameInitial,
                  ));
          Navigator.of(context).push(router);

          return (accessToken.body);
        } else {
          var router = new MaterialPageRoute(
              builder: (BuildContext context) => new Home());
          Navigator.of(context).push(router);
          print('connected');
        }
      }
    } on SocketException catch (_) {
      var router = new MaterialPageRoute(
          builder: (BuildContext context) => new NoNetworkL());
      Navigator.of(context).push(router);
      print('not connected');
    }

    return (null);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              color: Color.fromRGBO(58, 66, 86, 1.0),
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                  child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    CircleAvatar(
                      backgroundColor: Colors.white,
                      radius: 55.0,
                      child: new Image.asset(
                        'assets/images/logo.png',
                        scale: 2.2,
                        width: 120.0,
                        height: 120.0,
                        color: Colors.green.withOpacity(1.0),
                      ),
                    ),
                    Padding(padding: EdgeInsets.only(top: 50.0)),
                    Text(
                      "Quick Quiz",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 25.0,
                          fontWeight: FontWeight.bold),
                    )
                  ],
                ),
              )),
              Expanded(
                  flex: 1,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      CircularProgressIndicator(
                        valueColor:
                            new AlwaysStoppedAnimation<Color>(Colors.green),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: 20.0),
                      ),
                      Text(
                        "Please Wait",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18.0,
                            fontWeight: FontWeight.bold),
                      )
                    ],
                  ))
            ],
          )
        ],
      ),
    );
  }
}
