import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:intl/intl.dart';

import '../Models/hrmModels/jobDescriptionResponse.dart';
import '../Utils/BackgroundLocationService.dart';
import '../Utils/WebSocketManager.dart';
import '../Utils/background_service.dart';

class HomescreenNotifier extends ChangeNotifier {
  String isBatterIgnoredText = 'Unknown';
  String _username = "";
  String _email = "";
  final String _curdate = "";
  String _empId = "";
  String _session = "";
  String _requestId = "";
  String _webPageUrl = "";
  String _whizzdomPageUrl = "";
  String _roleStatus = "";
  int _att_status = 0;
  bool _isLoading = true;
  var _Sessionid;
  String? _onlineStatus = "Offline";

  String get username => _username;

  String get email => _email;

  String get curdate => _curdate;

  String get empId => _empId;

  String get session => _session;

  String get requestId => _requestId;

  String get webPageUrl => _webPageUrl;

  String get whizzdomPageUrl => _whizzdomPageUrl;

  String get roleStatus => _roleStatus;

  int get att_status => _att_status;

  get Sessionid => _Sessionid;

  String? get onlineStatus => _onlineStatus;

  WebSocketManager webSocketManager = WebSocketManager(
    onConnectSuccess: () {
      // Handle on connect success callback
    },
    onMessage: (message) {
      // Handle on message callback
    },
    onClose: () {
      // Handle on close callback
    },
    onConnectFailed: () {
      // Handle on connect failed callback
    },
  );

  Future<void> DashboardApiFunction(context) async {
    try {
      _empId = await SharedpreferencesService().getString("UserId") ?? "";
      _username = await SharedpreferencesService().getString("UserName") ?? "";
      _email = await SharedpreferencesService().getString("UserEmail") ?? "";
      _session = await SharedpreferencesService().getString("Session_id") ?? "";
      _roleStatus = await SharedpreferencesService().getString("roles") ?? "";
      _requestId =
          await SharedpreferencesService().getString("attendRequestId") ?? "";
      var lastLocationTime = await SharedpreferencesService().getString(
        "lastLocationTime",
      );
      notifyListeners();

      print("lastLocationTime:$lastLocationTime");
      if (await SharedpreferencesService().getString("redirectUrl") == null) {
        _webPageUrl =
            "https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session";
        _whizzdomPageUrl =
            "https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session&login_type=whizzdom&redirect_url=https://whizzdom.gengroup.in";
      } else {
        _webPageUrl =
            "https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session&redirect_url=${SharedpreferencesService().getString("redirectUrl").toString()}";
        _whizzdomPageUrl =
            "https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session&login_type=whizzdom&redirect_url=${SharedpreferencesService().getString("redirectUrl").toString()}";
      }
      notifyListeners();
      if (kDebugMode) {
        print("s:$session");
        print("r:$roleStatus");
        print(roleStatus.length);
      }

      final data = await ApiCalling.DashboardFunctionApi(
        empId ?? "",
        session ?? "",
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          _isLoading = false;
          _att_status = data.attStatus ?? 0;
          // BatteryOptimisation();
          // checkOptimisation(),
          if (_att_status == 0) {
            webSocketManager.close();
            await BackgroundLocationService.stopLocationService();

            _onlineStatus = "Offline";

            // print("setstatus:$setstatus");
          } else if (_att_status == 1) {
            // print("att_status:$att_status");
            DateTime Date1;
            DateTime Date2;
            String getCurrentTime() {
              DateTime now = DateTime.now(); // Get current time
              DateFormat formatter = DateFormat(
                'HH:mm:ss',
              ); // Define the format
              return formatter.format(now); // Format and return the time string
            }

            String currentTime = getCurrentTime();

            // var currentTime =  DateTime.now();
            // var df =  DateFormat('HH:mm:ss').format(currentTime);

            if (lastLocationTime != null) {
              Date1 = DateFormat('HH:mm:ss').parse(currentTime);
              Date2 = DateFormat('HH:mm:ss').parse(lastLocationTime);

              Duration difference = Date1.difference(Date2);
              var diff = difference.inSeconds / 1000;
              // print(diff);
              if (diff >= 20) {
                // print("diff");
                _onlineStatus = "Offline";
              } else {
                // print("nodiff");
                _onlineStatus = "Online";
              }
            } else {
              // print("Status knlknn offine");
            }
            await BackgroundLocationService.startLocationService(context);
            // print("setstatus:$setstatus");
          } else if (_att_status == 2) {
            // print("att_status:$att_status");
            webSocketManager.close();
            await BackgroundLocationService.stopLocationService();

            _onlineStatus = "Offline";

            // print("setstatus:$setstatus");
          }
          notifyListeners();
        } else if (data.sessionExists == 0) {
          SharedpreferencesService().clearPreferences();
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => LoginScreen()),
          );
          notifyListeners();
          // print(data.toString());
        }
      } else {
        // print("Something went wrong, Please try again.")
      }
    } on Exception catch (e) {
      print("$e");
    }
  }
}
