//import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:nfc_manager/platform_tags.dart';
import 'services/storage.dart' as storage;
//import 'services/device_info.dart' as device_info;
import 'classes/named_route_args.dart';
import 'package:location/location.dart';
import 'common_widgets/custom_icon_button.dart';
import 'classes/common_classes.dart';
import 'package:nfc_manager/nfc_manager.dart';
import "package:hex/hex.dart";
import 'package:geolocator/geolocator.dart' as geolocator;
import 'package:geocoding/geocoding.dart' as geocoding;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:simple_barcode_scanner/simple_barcode_scanner.dart';
import 'dart:io';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:lite_rolling_switch/lite_rolling_switch.dart';
import 'package:fluttertoast/fluttertoast.dart';
//AutoUpdateApk aua = new AutoUpdateApk(getApplicationContext(), UPDATE_URL);



//import 'package:flutter_local_notifications/flutter_local_notifications.dart';
//import 'package:timezone/data/latest_all.dart' as tz;
//import 'package:timezone/timezone.dart' as tz;

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

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with TickerProviderStateMixin{
  String appDomain = "iotechnic.eu";



  bool isSupported = true;

  bool _showNFClogo = false;
  bool _reportButtonDisabled = true;
  final bool _nfcOk = false;
  final bool _deviceRegistered = false;
  bool _initOK = false;
  bool _isApiKeyValid = false;
  bool _isScanVisible = false;
  bool _isLocationMocked=false;
  bool _isLocationValid=false;
  geolocator.Position? _currentPosition;
  late LocationData _currentLocation;
  String _currentAddress = "";
  String result = "";
  String accessName = "";
  String accessMsg = "";
  String accessWorktime = "";
  String accessDateTime = "";
  String accessLocation = "";
  String appVersion = "";
  String appCode = "";
  String qrdata="";
  String currentWorkState="";
  QRCodeModel currentQRcode=QRCodeModel();
  WorkStateModel workState=WorkStateModel();
  EmployeeArguments? ea;
  EmployeePageArguments employeePageArgs = EmployeePageArguments();

  //device_info.DeviceInfo di=device_info.DeviceInfo();
  //late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  //var deviceData = <String, dynamic>{};

  //IMEI
  String? deviceUUID1;
  String? deviceUUID2;
  String? deviceBrand="Mobile";



  Future ?apiKey  ;
  bool apiKeyValid=false;
 // Map<String, dynamic> _deviceData = <String, dynamic>{};
// Location
  final Location location = Location();
  bool _loading = false;
  LocationData? _location;
  String? _error;

  late final AnimationController _controller = AnimationController(
    duration: const Duration(seconds: 1),
    vsync: this,
    lowerBound: 0.5,
    upperBound: 1.0,
    value: 1,
  )..repeat(reverse: true);
  late final Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeInOutCirc,
  );

// Aktuális QR kód lekérése szervertől
  Future<bool> getQRCode(String userApiKey) async {
    if (userApiKey.isEmpty) return false;
    var url = "http://$appDomain/apiGetQRCode/$userApiKey";
    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      var resp = jsonDecode(response.body);
      currentQRcode = QRCodeModel.fromJson(resp);
      setState(() {
        qrdata=currentQRcode.qrCode!;
      });
      return true;
    }

    return false;
    //return resp.map<EmployeeLs>((m) => EmployeeLs.fromJson(m)).toList();
  }

// Aktuális Munkaidő állapot lekérése szervertől
  Future<bool> getWorkState(String userApiKey) async {
    if (userApiKey.isEmpty) return false;
    var url = "http://$appDomain/apiGetWorkState/$userApiKey";
    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      var resp = jsonDecode(response.body);
      workState = WorkStateModel.fromJson(resp);
      setState(() {
        currentWorkState=workState.workState!;
      });
      return true;
    }

    return false;
    //return resp.map<EmployeeLs>((m) => EmployeeLs.fromJson(m)).toList();
  }

  Future<bool> checkApiKeyValidity(String userApiKey) async {
    if (userApiKey.isEmpty) return false;
    var url = "http://$appDomain/apiemployee/$userApiKey";
    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      var resp = jsonDecode(response.body);
      ea = EmployeeArguments.fromJson(resp);
      setState(() {
        _reportButtonDisabled = false;
      });
      if (ea?.mobilePortalAccessEnabled == false) {
        _showAccessDeniedDialog();
      }
      employeePageArgs = EmployeePageArguments(
          name: ea?.name,
          id: ea?.id,
          apiKey: userApiKey,
          isForeman: ea?.isForeman,
          mobilePortalAccessEnabled: ea?.mobilePortalAccessEnabled);
      setState(() {
        _reportButtonDisabled = employeePageArgs.isForeman!;
      });
      if (employeePageArgs.id!.isNotEmpty) {
        return true;
      } else {
        return false;
      }
    }

    return false;
    //return resp.map<EmployeeLs>((m) => EmployeeLs.fromJson(m)).toList();
  }

  @override
  void dispose(){
    NfcManager.instance;
    _controller.dispose();
    NfcManager.instance;
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.dispose();
  }
  Future<bool> getDeviceUUID() async{
    storage.SecureStorage sc= storage.SecureStorage();

    deviceUUID1= await sc.readSecureData('UUID1');
    deviceUUID2= await sc.readSecureData('UUID2');
    if (deviceUUID1!.startsWith("No data found!")  || deviceUUID2!.startsWith("No data found!")) {
      return false;
    } else {
      return true;
    }
  }

  Future<bool> _checkUUIDS() async {
    storage.SecureStorage sc= storage.SecureStorage();
    //sc.deleteSecureData('API');
    bool resAPI= await storage.SecureStorage().checkContainsKey('API');// sc.checkContainsKey('API');
    bool  resUUID1= await storage.SecureStorage().checkContainsKey('UUID1') ;
    bool  resUUID2= await storage.SecureStorage().checkContainsKey('UUID2') ;
    if (resAPI==false || resUUID1==false || resUUID2==false)
      {
        return false;
      }
    return true;
  }
  Future<void> _registerDevicePage() async {

  }
  @override
  void initState()  {
    // TODO: implement initStateA
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

      storage.SecureStorage sc= storage.SecureStorage();
      //sc.deleteSecureData('API');
      //Future<bool> resAPI= storage.SecureStorage().checkContainsKey('API');// sc.checkContainsKey('API');
      //Future<bool> resUUID1=  storage.SecureStorage().checkContainsKey('UUID1') ;
      //Future<bool> resUUID2=  storage.SecureStorage().checkContainsKey('UUID2') ;

        //_isApiKeyValid=value;
        //apiKeyValid=value;
      _checkUUIDS().then((val){
    if (val==false)
        {

            Navigator.pushNamed(
                context, '/register', arguments: DeviceArguments(
              //deviceData['id'], deviceData['device'], deviceData['brand'])).then((value)
                //deviceUUID1!, deviceUUID2!, deviceBrand!)).then((value) {
                "", "", "")).then((value) {
              Future<String> userApiKey = sc.readSecureData("API");
              userApiKey.then((apiKey) =>
                  checkApiKeyValidity(apiKey).then((apiKeyState) {
                    // print("API key State: $apiKeyState");

                    setState(() {
                      _isApiKeyValid = apiKeyState;
                      if (ea?.isForeman == true) {
                        _reportButtonDisabled = false;
                      }
                      if (ea?.mobilePortalAccessEnabled == true) {
                        NfcManager.instance.isAvailable().then((nfcState) {
                          if (_isApiKeyValid && !_isLocationMocked) {
                            _showNFClogo = true;
                            _tagRead();
                          }
                          else {
                            _showNFClogo = false;
                          }
                        });
                        getWorkState(apiKey);
                        getQRCode(apiKey);
                      }
                      _getLocation();
                      // _getCurrentLocation();
                      _isApiKeyValid = apiKeyState;
                    });
                  }
                  )
              );
            });

        }
        else
        {
          getDeviceUUID();
          Future<String> userApiKey=sc.readSecureData("API");
          userApiKey.then((apiKey) => checkApiKeyValidity(apiKey).then((apiKeyState) {
           // print("API key State: $apiKeyState");

            setState(() {
              _isApiKeyValid = apiKeyState;
              if (ea == null) return;
              if (ea?.isForeman==true)
              {
                _reportButtonDisabled=false;
              }
              if (ea?.mobilePortalAccessEnabled==true)
              {
                NfcManager.instance.isAvailable().then((nfcState){
                  if (_isApiKeyValid && !_isLocationMocked)
                  {
                    _showNFClogo=true;
                    _tagRead();
                  }
                  else
                  {
                    _showNFClogo=false;
                  }
                } );
                getWorkState(apiKey);
                getQRCode(apiKey);
               }
              _getLocation();
              // _getCurrentLocation();
              _isApiKeyValid = apiKeyState;
            });
          }
          )
          );

        }

      });
      //sc.writeSecureData("API", deviceData['id']);
      //sc.checkContainsKey('API');
      //sc.readSecureData("API");
    //);

    _getLocation();
    PackageInfo.fromPlatform().then((value) => {
    appCode=value.buildNumber,
        appVersion=value.version
    });//getAppVersion() as PackageInfo;



    if (!mounted) return;
    setState(() {
      _initOK=true;
    //  _deviceData = deviceData;

    });
    //getWorkState(apiKey as String);

    //apiKey=//_getApiKey();
//    _storage.write(key: 'API', value: _deviceData['id']);
  }
  Future<void> _getLocation() async {
    setState(() {
      _error = null;
      _loading = true;
      _isLocationValid=false;
      _isScanVisible=false;
    });
    try {
      final locationResult = await location.getLocation();
      setState(() {
        _location = locationResult;
        _loading = false;
          _isLocationValid = true;
          _isLocationMocked=locationResult.isMock!;
          _isScanVisible = true;
          _currentLocation=locationResult;
          _getAddressFromLatLng(locationResult.latitude,locationResult.longitude);

      });
    } on PlatformException catch (err) {
      setState(() {
        _error = err.code;
        _loading = false;
        _isLocationValid=false;
        _isScanVisible=false;
      });
    }
  }

  /*Future<void> _showMyDialog(String message1) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Figyelmeztetés'),
          content: const SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message1 as String),
                Text('Would you like to approve of this message?'),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('Bezár'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }*/


  Widget nfcLogo() {
    if (_location?.isMock==true) {
      return const Padding(
        padding: EdgeInsets.all(8.0),
        child: Image(
          color: Colors.white,
          image: AssetImage('graphics/nfcdenied.png'),
          width: 128,
        ),
      );
    } else {
      return ScaleTransition(
        scale: _animation,
        child: const Padding(
          padding: EdgeInsets.all(8.0),
          child: Image(
            color: Colors.white,
            image: AssetImage('assets/nfc.png'),
            width: 128,
          ),
        ),
      );
    }
  }

  _loginQR(qrCode) async {
    setState(() {
      _showNFClogo = false;
    });

    bool r=await getDeviceUUID();
    if (!r) return;
   // _showMyDialog();
    //DeviceInfo devInfo = _getDeviceInfo() as DeviceInfo;
    _getLocation();
    String indexRequest = '{'
        '"cmd":"ACCESSNOGEOQR",'
        '"CID1":"$deviceUUID1",' //$"{deviceData['id']}",'
        '"CID2":"$deviceUUID2 $deviceBrand",'    //"${deviceData['device']} ${deviceData['brand']}",'
        '"address":"$_currentAddress",'
        '"qrCode":"$qrCode",'
        '"LAT":"${_currentLocation.latitude}",'
        '"LON":"${_currentLocation.longitude}",'
        '"mode":"GETAWAY"}';

    debugPrint('Connecting...');
    //AESEncryption enc = new AESEncryption();
    //enc.encryptMsg(indexRequest);
    //connect to google port 80
    Socket.connect("iotechnic.eu", 8080).then((socket) {
      if (kDebugMode) {
        print('Connected to: '
            '${socket.remoteAddress.address}:${socket.remotePort}');
      }

      //Establish the onData, and onDone callbacks
      socket.listen((data) {
        //print(new String.fromCharCodes(data).trim());
        var decoded = utf8.decode(data);
        //var jsonString = json.encode(new String.fromCharCodes(data).trim());
        Map<String, dynamic> resp = jsonDecode(decoded);
        debugPrint(decoded);
        debugPrint(resp['data']);
        getWorkState(employeePageArgs.apiKey as String);
        if (resp['data'] == 'VALID CODE') {
          setState(() {
            result = "";
            accessName = resp['employeeName'];
            accessMsg = resp['message'];
            accessLocation = resp['city'];
            accessWorktime = resp['worktime'];
            accessDateTime = resp['datetime'];
          });
        } else {
          setState(() {
            result = resp['data'];
            accessName = "";
            accessMsg = "";
            accessLocation = "";
            accessWorktime = "";
            accessDateTime = "";
          });
        }
        Timer.periodic(const Duration(seconds: 5), (timer) {
          //print(DateTime.now());
          timer.cancel();
          result = "Üzemkész";
          accessName = "";
          accessMsg = "";
          accessLocation = "";
          accessWorktime = "";
          accessDateTime = "";
          setState(() {
            _showNFClogo = true;
          });
        });
      }, onDone: () {
        if (kDebugMode) {
          print("Done");
        }
        socket.destroy();
      });

      //Send the request
      debugPrint("Request->$indexRequest");
      socket.write(indexRequest);
      //socket.write(enc);
      socket.flush();
    });
  }
  _login(rfid) async {
    setState(() {
      _showNFClogo = false;
    });
    //DeviceInfo devInfo = _getDeviceInfo() as DeviceInfo;
    bool r=await getDeviceUUID();
    if (!r) return;
    String indexRequest = '{'
        '"cmd":"ACCESSNOGEO",'
       // '"CID1":"${deviceData['id']}",'
       // '"CID2":"${deviceData['device']} ${deviceData['brand']}",'
        '"CID1":"$deviceUUID1",'
        '"CID2":"$deviceUUID2 $deviceBrand",'
        '"address":"$_currentAddress",'
        '"rfid":"$rfid",'
        '"LAT":"${_currentLocation.latitude}",'
        '"LON":"${_currentLocation.longitude}",'
        '"mode":"GETAWAY"}';

    debugPrint('Connecting...');
    //AESEncryption enc = new AESEncryption();
    //enc.encryptMsg(indexRequest);
    //connect to google port 80
    Socket.connect("iotechnic.eu", 8080).then((socket) {
      if (kDebugMode) {
        print('Connected to: '
          '${socket.remoteAddress.address}:${socket.remotePort}');
      }

      //Establish the onData, and onDone callbacks
      socket.listen((data) {
        //print(new String.fromCharCodes(data).trim());
        var decoded = utf8.decode(data);
        //var jsonString = json.encode(new String.fromCharCodes(data).trim());
        Map<String, dynamic> resp = jsonDecode(decoded);
        debugPrint(decoded);
        debugPrint(resp['data']);
        getWorkState(employeePageArgs.apiKey as String);
        if (resp['data'] == 'VALID CODE') {
          setState(() {
            result = "";
            accessName = resp['employeeName'];
            accessMsg = resp['message'];
            accessLocation = resp['city'];
            accessWorktime = resp['worktime'];
            accessDateTime = resp['datetime'];
          });
        } else {
          setState(() {
            result = resp['data'];
            accessName = "";
            accessMsg = "";
            accessLocation = "";
            accessWorktime = "";
            accessDateTime = "";
          });
        }
        Timer.periodic(const Duration(seconds: 5), (timer) {
          //print(DateTime.now());
          timer.cancel();
          result = "Üzemkész";
          accessName = "";
          accessMsg = "";
          accessLocation = "";
          accessWorktime = "";
          accessDateTime = "";
          setState(() {
            _showNFClogo = true;
          });
        });
      }, onDone: () {
        if (kDebugMode) {
          print("Done");
        }
        socket.destroy();
      });

      //Send the request
      debugPrint("Request->$indexRequest");
      socket.write(indexRequest);
      //socket.write(enc);
      socket.flush();
    });
  }

  _getAddressFromLatLng(lat,lon) async {
    try {
      List<geocoding.Placemark> placemarks = await geocoding.placemarkFromCoordinates(
          //_currentPosition!.latitude, _currentPosition!.longitude);
      lat,lon);
      geocoding.Placemark place = placemarks[0];

      setState(() {
        _currentAddress =
        "${place.locality}, ${place.thoroughfare}, ${place.subThoroughfare}";
        result = "Üzemkész";
      });
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  Future<void> _showAccessDeniedDialog() {
    return showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('Hozzáférés elutasítva'),
            content: const Text('Az applikációs hozzáférése nincs engedélyezve!'),
            actions: <Widget>[
              TextButton(
                  onPressed: () {
                    SystemNavigator.pop();
                  },
                  child: const Text('Kilépés')),
            ],
          );
        });
  }
  void _tagRead() {
    const HexEncoder(upperCase: true);

    //print(HEX.encode(const [1, 2, 3, 12]));
    NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
      MifareClassic? nfca = MifareClassic.from(tag);
      String nfcResult = HEX.encode(nfca!.identifier).toUpperCase();
      if (kDebugMode) {
        print("TAG: $nfcResult");
      }
      _getLocation();

      _login(nfcResult);
      //ag.data;
      /* setState(() {
        tagOk = true;
      });*/
      /* if (tagOk = true) {
        Future.delayed(Duration(milliseconds: 3000), () {
          setState(() {
            tagOk = false;
          });

          NfcManager.instance.stopSession();
        });
      }*/
    });
  }
  showQRCode() {
    var _WorkTimeState=false;
   // _showNotification();
    showDialog(
        context: context,
        builder: (context) {
          if (currentWorkState.compareTo('DOLGOZIK')==0) _WorkTimeState=true;
          if (currentWorkState.compareTo('VÉGZETT')==0) _WorkTimeState=false;
          return AlertDialog(
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(
                  20.0,
                ),
              ),
            ),
            contentPadding: const EdgeInsets.only(
              top: 10.0,
            ),
            title: Text(
              "Státusz:  $currentWorkState",
              style: const TextStyle(fontSize: 24.0),
              textAlign: TextAlign.center,
            ),
            content: SingleChildScrollView(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[

                  Container(
                    padding: const EdgeInsets.all(8.0),

                      child: qrdata.isNotEmpty ? QrImageView(
                      data: qrdata,
                      version: QrVersions.auto,
                      size: 200.0,
                        embeddedImageEmitsError: true,
                    )
                    : const Text('HIBA!'),
                  ),
                  Container(
                    padding: const EdgeInsets.all(8.0),
                    child:                 ElevatedButton(
                      child: const Text('Bezár'),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(8.0),
                    child: LiteRollingSwitch(
                    value: _WorkTimeState,
                    width: 200,
                    textOn: currentWorkState,
                    textOff: currentWorkState,
                    colorOn: Colors.deepOrange,
                    colorOff: Colors.blueGrey,
                    iconOn: Icons.work,
                    iconOff: Icons.work_off,
                    animationDuration: const Duration(milliseconds: 300),
                    onChanged: (bool state) {
                      if (kDebugMode) {
                        print('turned ${(state) ? 'on' : 'off'}');
                      }
                    },
                    onDoubleTap: () {},
                    onSwipe: () {
                      if (kDebugMode) {
                        print('Swiped!');
                      }
                      _loginQR(currentQRcode.qrCode);
                      Navigator.pop(context);
                    },
                    onTap: () {},
                  ),
                    /*ElevatedButton(
                      child: currentWorkState.compareTo('DOLGOZIK')==0
                        ?const Text('Munkaidő befejezés', style: TextStyle(fontSize: 16))
                          :const Text('Munkaidő kezdés', style: TextStyle(fontSize: 16),),
                      onPressed: () {
                        _loginQR(currentQRcode.qrCode);
                        Navigator.pop(context);
                      },
                    ),*/
                  ),
                ],
              ),
            ),
          );
        });
  }
  @override
  Widget build(BuildContext context) {
    //var qrResult;
    /*return MaterialApp(
      theme: ThemeData(
        useMaterial3: true,
        colorSchemeSeed: const Color(0x9f4376f8),
      ),*/
     //return
      // bool _positionIsMocked = _location?.isMock ?? false;//_currentPosition?.isMocked ?? false;
     return
       Scaffold(
           appBar: AppBar(
           title: Text("Mobile Portal  V$appCode$appVersion"),//_getAppBarTitle()),
             actions: <Widget>[
               IconButton(

               icon: const Icon(Icons.qr_code),
             tooltip: 'Bejelentkezés',
             onPressed:  (_isApiKeyValid==true && _isLocationValid==true && _isLocationMocked==false) ? () {
                 getWorkState(employeePageArgs.apiKey as String);
                 getQRCode(employeePageArgs.apiKey as String);
                  showQRCode();
             }
             : null,
           ),
           ],

    elevation: 4,
    ),
         /*  floatingActionButton: new Visibility(
             visible: _isScanVisible && _showNFClogo && _isApiKeyValid ,
             child: new FloatingActionButton.extended(
               icon: Icon(Icons.qr_code),
               label: Text("Beolvasás"),
               //onPressed: _scanQR,
               onPressed: () async {
    MobileScanner(
    // fit: BoxFit.contain,
    controller: MobileScannerController(
    detectionSpeed: DetectionSpeed.normal,
    facing: CameraFacing.front,
    torchEnabled: true,
    ),
    onDetect: (capture) {
    final List<Barcode> barcodes = capture.barcodes;
    final Uint8List? image = capture.image;

    for (final barcode in barcodes) {
    qrResult=barcode;
    debugPrint('Barcode found! ${barcode.rawValue}');
    }
    setState(() {
    if (qrResult is String) {
    //result = res;
    _login(qrResult);
    }
    }

    );
    },
    );
    }),//floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
           ),*/
           floatingActionButton: Visibility(
             visible: _isScanVisible && _showNFClogo && _isApiKeyValid ,
             child: FloatingActionButton.extended(
               icon: const Icon(Icons.qr_code),
               label: const Text("Beolvasás"),
               //onPressed: _scanQR,
               onPressed: () async {
                 var qrResult = await Navigator.push(
                     context,
                     MaterialPageRoute(
                       builder: (context) => const SimpleBarcodeScannerPage(),
                     ));
                 setState(() {
                   if (qrResult is String) {
                     //result = res;
                     _loginQR(qrResult);
                   }
                 });
               },
             ),
             //floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
           ),
    body:

       Padding(
         padding: const EdgeInsets.all(14.0),
         child: _initOK || _loading
             ? Column(
           mainAxisAlignment: MainAxisAlignment.spaceBetween,
           crossAxisAlignment: CrossAxisAlignment.center,
           children: <Widget>[
             Flexible(
             flex: 1,
             //fit: FlexFit.tight,
             child:
             SizedBox(
               //width: 300,
               height: 50,
               //color: Colors.amber,
               child:

             Column(
               children: <Widget>[
             Text(currentWorkState),
             Text(currentQRcode.name  ?? "",
             style: const TextStyle(
               fontSize: 16,
               fontWeight: FontWeight.bold
             ),
             ),
               ],
             ),
             ),
             ),
             Flexible(
               flex: 2,
               fit: FlexFit.tight,
               child: Row(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: <Widget>[
                   Flexible(
                     flex: 1,
                     fit: FlexFit.tight,
                     child: Container(
                       width: 200,
                       height: 200,
                       decoration: BoxDecoration(
                         //borderRadius: BorderRadius.circular(10),
                         color: Colors.indigo[600],
                       ), //BoxDecoration
                       child: Transform.scale(
                         scale: 2,
                         child: CustomIconButton(
                             icon: const Icon(Icons.pending_actions),
                             isDisabled: _isApiKeyValid == false,
                             color: _isScanVisible ||
                                 !_isLocationMocked ||
                                 _isApiKeyValid == true
                                 ? Colors.indigo[600]!
                                 : Colors.grey.shade50,
                             onPressed: () {
                               if (_isApiKeyValid == true) {
                                 Navigator.pushNamed(context, '/wtdetails',
                                     arguments: {
                                       'userArgs': employeePageArgs,
                                       'dataArgs': null
                                     });
                               }
                             }),
                       ),
                     ), //Container
                   ), //Flexible
                   const SizedBox(
                     width: 10,
                   ), //SizedBox
                   Flexible(
                     flex: 1,
                     fit: FlexFit.tight,
                     child: Container(
                       width: 200,
                       height: 200,
                       decoration: BoxDecoration(
                         //borderRadius: BorderRadius.circular(10),
                         color: Colors.indigo[600],
                       ),
                       child: Transform.scale(
                         scale: 2,
                         child: CustomIconButton(
                           icon: const Icon(Icons.list),
                           isDisabled: _reportButtonDisabled ||
                               _isApiKeyValid == false,
                           color: Colors.indigo[600]!,
                           onPressed: () {
                             Navigator.pushNamed(context, '/reportNav',
                                 arguments: {
                                   'userArgs': employeePageArgs,
                                   'dataArgs': null
                                 });
                             //WorkTimeDetails()));
                           },
                         ), //BoxDecoration
                       ), //Container
                     ),
                   ) //Flexible
                 ],
               ), //Row
             ),

             /*const SizedBox(
               height: 5,
             ),*/ //SixedBox
             Flexible(
               flex: 4,
               fit: FlexFit.tight,
               child: Container(
                   width: 380,
                   height: 200,
                   decoration: BoxDecoration(
                       borderRadius: BorderRadius.circular(10),
                       color: Colors.blue), //BoxDecoration
                   child: _isApiKeyValid == true
                       ? Column(
                     children: <Widget>[
                       const SizedBox(
                         height: 10,
                       ),
                       if (!_isLocationValid) ...[
                         //Text("Várakozás heladatokra..."),
                         const CircularProgressIndicator(
                           color: Colors.white,
                         ),
                       ],
                       if (!_isScanVisible) ...[
                         TextButton(
                           child: const Text(
                             "Várakozás heladatokra...",
                             style: TextStyle(
                               fontSize: 24.0,
                               fontWeight: FontWeight.bold,
                               color: Colors.white,
                             ),
                           ),
                           onPressed: () {
                             _getLocation();
                           },
                         ),
                         const SizedBox(
                           height: 30,
                         ),
                         const Icon(
                           Icons.location_on_outlined,
                           size: 64,
                           color: Colors.white,
                         ),
                       ],
                       if (_isScanVisible && !_showNFClogo)
                         Column(
                             mainAxisAlignment:
                             MainAxisAlignment.center,
                             children: <Widget>[
                               Text(
                                 accessName,
                                 style: const TextStyle(
                                     fontSize: 30.0,
                                     fontWeight: FontWeight.normal),
                               ),
                               Text(
                                 accessMsg,
                                 style: const TextStyle(
                                     fontSize: 30.0,
                                     fontWeight: FontWeight.bold),
                               ),
                               Text(
                                 accessDateTime,
                                 style: const TextStyle(
                                     fontSize: 30.0,
                                     fontWeight: FontWeight.bold),
                               ),
                               Text(
                                 accessWorktime,
                                 style: const TextStyle(
                                     fontSize: 30.0,
                                     fontWeight: FontWeight.bold),
                               ),
                               Text(
                                 accessLocation,
                                 style: const TextStyle(
                                     fontSize: 16.0,
                                     fontWeight: FontWeight.bold),
                               ),
                             ]),
                       if (_isScanVisible && _showNFClogo) ...[
                         Column(
                         mainAxisAlignment:
                         MainAxisAlignment.center,
                         children: <Widget>[
                         Text(
                         _currentAddress,
                         style: const TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold),
                          ),
                          Text(
                            'Location: ${_error ?? result}',
                         // result,
                          style: const TextStyle(
                          color: Colors.white,
                          fontSize: 30.0,
                          fontWeight: FontWeight.bold),
                          ),
                          ]),


                         const SizedBox(
                           height: 20,
                         ),
                         if (_showNFClogo)
                           nfcLogo()

                       ],
                     ],
                   )
                       : const Column(
                     mainAxisAlignment: MainAxisAlignment.center,
                     children: [
                       Text(
                         'Hozzáférés nem engedélyezett!',
                         textAlign: TextAlign.center,
                         style: TextStyle(
                             color: Colors.white,
                             fontSize: 30.0,
                             fontWeight: FontWeight.bold),

                       ),
                     ],
                   )), //Container
             ), //Flexible

           ],
         )
             : Container(
             alignment: Alignment.topCenter,
             margin: const EdgeInsets.only(top: 20),
             child: const CircularProgressIndicator(
               value: 0.8,
             )) //Column
     )

       ); //Padding

  }


    /*Scaffold(
        appBar: AppBar(
          title: Text(_getAppBarTitle()),
          elevation: 4,
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              'Location: ${_error ?? '${_location ?? "unknown"}'}',
              style: Theme.of(context).textTheme.bodyLarge,
            ),
            Row(
              children: <Widget>[
                ElevatedButton(
                  onPressed: _getLocation,
                  child: _loading
                      ? const CircularProgressIndicator(
                    color: Colors.white,
                  )
                      : const Text('Get'),
                )
              ],
            ),
          ],
        )
      );*/
   // );
  }


