import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:rkm/screens/login/sync_login_screen.dart';
import 'package:rkm/service/api/url_api_const.dart';
import 'package:rkm/config/const_variable.dart';
import '../service/db/db_sqlite_load.dart';
import '../service/shared_preferences/shared_preferences_service.dart';
import 'login/login_saved_screen.dart';

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

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {


  @override
  void initState() {
    super.initState();
    DbSqliteLoad().intialDB().then((value){
      final PrefService _prefService = PrefService();
      _prefService.readCacheModel('user', 'password', 'city', 'mode').then((list){
        if(list[0] == null){
          Navigator.pushReplacementNamed(context, '/login_load');
        }else{
          timer(list);
        }
      });
    });
  }

  timer(List list)async{
   await DbSqliteLoad().intialDB().then((db)async{
     List dataControl = await db.query('MUNICIPIOS');
     List dataCitizen = await db.query('CIDADAOS');
     if(dataControl.length != 0){
       var query = "SELECT * FROM CONTROLE_INTERNO";
       dataControl = await db.rawQuery(query);
       String? url;
       if(list[3]=='desenvolvimento'){
         url = UrlApiConst.ApiUrlDesenvolvimento;
       }else if(list[3]=='homologacao'){
         url = UrlApiConst.ApiUrlHomologacao;
       }else{
         url = UrlApiConst.ApiUrlOnline;
       }
       if(dataCitizen.length != 0){
         Navigator.push(
             context,
             MaterialPageRoute(builder: (context) => LoginSavedScreen(listControl: dataControl,)),
           );
       }else{
             Navigator.push(
               context,
               MaterialPageRoute(builder: (context) => SyncLoginScreen()),
             );
           }
     }else{
         Navigator.pushReplacementNamed(context, '/login_load');
     }
   });
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Container(
        decoration: ConstVariable().backgroundGradient,
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset('assets/images/logo.PNG',width: width*0.5,),
              CircularProgressIndicator()
            ],
          ),
        ),
      ),
    );
  }
}
