// import 'dart:io';

// import 'package:device_info_plus/device_info_plus.dart';

import 'dart:async';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';

class DeviceHelper {
  static Future<String> getDeviceFingerprint() async {
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    var deviceData;

    try {
      if (Platform.isAndroid) {
        // Fetch Android-specific device information
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        deviceData = androidInfo.toMap(); // Convert to a map for easier access
        // Log.print('deviceData: ${jsonEncode(deviceData)}');
      } else if (Platform.isIOS) {
        // Fetch iOS-specific device information
        IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
        deviceData = iosInfo.toMap(); // Convert to a map for easier access
      } else if (Platform.isMacOS) {
        // Fetch macOS-specific device information
        MacOsDeviceInfo macInfo = await deviceInfoPlugin.macOsInfo;
        deviceData = macInfo.toMap();
      } else {
        throw UnsupportedError('Unsupported platform');
      }

      String deviceId = 'unknown';
      if (Platform.isAndroid) {
        deviceId = deviceData['fingerprint'] ?? 'unknown';
      } else if (Platform.isIOS) {
        deviceId = deviceData['identifierForVendor'] ?? 'unknown';
      } else if (Platform.isMacOS) {
        deviceId = deviceData['systemGUID'] ?? 'unknown';
      }

      final String deviceModel = deviceData['model'] ?? 'unknown';

      final String fingerprint = '${deviceId}_$deviceModel';
      print(fingerprint);
      return (fingerprint);
    } catch (e) {
      throw Exception('Failed to generate device fingerprint');
    }
  }
}

// class SecurityHelper {
//   /// Performs security checks and handles potential risks
//   static Future<void> performSecurityChecks() async {
//     bool isNotTrust = false;
//     bool isJailBroken = false;
//     bool isRealDevice = true;
//     bool isOnExternalStorage = false;
//     bool checkForIssues = false;
//     bool isDevMode = false;
//     bool isTampered = false;
//     String bundleId = "";

//     try {
//       isNotTrust = await JailbreakRootDetection.instance.isNotTrust;
//       isJailBroken = await JailbreakRootDetection.instance.isJailBroken;
//       isRealDevice = await JailbreakRootDetection.instance.isRealDevice;
//       isOnExternalStorage =
//           await JailbreakRootDetection.instance.isOnExternalStorage;

//       List<JailbreakIssue> issues =
//           await JailbreakRootDetection.instance.checkForIssues;
//       checkForIssues = issues.isNotEmpty;

//       isDevMode = await JailbreakRootDetection.instance.isDevMode;

//       // Get Bundle ID
//       PackageInfo packageInfo = await PackageInfo.fromPlatform();
//       bundleId = packageInfo.packageName;
//       if (bundleId.isNotEmpty) {
//         // Pass the CORRECT bundle ID to isTampered
//         isTampered = await JailbreakRootDetection.instance.isTampered(bundleId);
//       }
//     } catch (e) {
//       debugPrint("Error during security checks: $e");
//       // Consider handling specific exceptions, not just general errors.
//     }

//     // Save values to storage (using GetStorage)
//     await box.write('isNotTrust', isNotTrust); // Use await for write operations
//     await box.write('isTampered', isTampered); // Use await
//     await box.write('isJailBroken', isJailBroken); // Use await

//     // debugPrint("Security Check Results:");
//     // debugPrint("isNotTrust: $isNotTrust");
//     // debugPrint("isJailBroken: $isJailBroken");
//     // debugPrint("isRealDevice: $isRealDevice");
//     // debugPrint("isOnExternalStorage: $isOnExternalStorage");
//     // debugPrint("checkForIssues: $checkForIssues");
//     // debugPrint("isDevMode: $isDevMode");
//     // debugPrint("isTampered: $isTampered");
//     // debugPrint("Bundle ID: $bundleId"); // Print the bundle ID

//     // Check for security risks and potentially show a warning
//     if (isJailBroken || isRealDevice == false || isTampered) {
//       //  print("security_warning".tr);  //using easy_localization
//       // Use a more robust approach to show a warning, like a dialog:
//       _showSecurityWarning();
//     }
//   }

//   /// Deletes all app data
//   static Future<void> clearAllData() async {
//     //await storage.deleteAll(); //  What's 'storage'?  Be specific.  Likely GetStorage as well.
//     await box.erase(); // Clear GetStorage data
//     exit(0); // This will terminate the app. Be VERY careful with this.
//   }

//   // static void _showSecurityWarning() {
//   //   // Show a dialog, navigate to an error screen, etc.
//   //   // Example using Get.dialog (if you use GetX):
//   //
//   //   Get.dialog(
//   //     AlertDialog(
//   //       title: Text("Security Warning".tr), // Or use localized string
//   //       content: Text(
//   //           "Potential security risks detected.  The application may not function correctly."
//   //               .tr), //Or use localized string
//   //       actions: [
//   //         TextButton(
//   //           onPressed: () async {
//   //             await storage.deleteAll();
//   //             await box.erase();
//   //             Get.back(); // Close the dialog
//   //             // Or, if you really must, exit the app (but give the user a chance!)
//   //             exit(0);
//   //           },
//   //           child: Text("OK"), // Or use a localized string
//   //         ),
//   //       ],
//   //     ),
//   //     barrierDismissible: false, // Prevent closing by tapping outside
//   //   );
//   // }
//   static void _showSecurityWarning() {
//     // Use an RxInt to track the remaining seconds.  This is the KEY!
//     RxInt secondsRemaining = 10.obs;

//     Get.dialog(
//       CupertinoAlertDialog(
//         title: Text("Security Warning".tr),
//         content: Column(
//           mainAxisSize: MainAxisSize.min,
//           children: [
//             Obx(() => Text(
//                   "Potential security risks detected. The application will close in @seconds seconds."
//                       .trParams({
//                     // Use trParams for placeholders
//                     'seconds': secondsRemaining.value.toString(),
//                   }),
//                   // Wrap the Text widget in Obx
//                 )),
//             SizedBox(height: 24), // More spacing before the progress bar
//             Obx(() => SizedBox(
//                 width: double.infinity, // Make progress bar full width
//                 child: CupertinoActivityIndicator(
//                   // in case of loading
//                   radius: 15,
//                   animating: true,
//                 ))),
//             SizedBox(height: 8),
//             Obx(() => ClipRRect(
//                   borderRadius: BorderRadius.circular(8), // Rounded corners
//                   child: LinearProgressIndicator(
//                     value: secondsRemaining.value / 10,
//                     backgroundColor: Colors.grey.shade300, // Lighter background
//                     valueColor: AlwaysStoppedAnimation<Color>(
//                         CupertinoColors.systemRed), // iOS-style red
//                     minHeight: 8, // Slightly thicker progress bar
//                   ),
//                 )),
//           ],
//         ),
//       ),
//       barrierDismissible: false,
//     );

//     Timer.periodic(Duration(seconds: 1), (timer) {
//       secondsRemaining.value--;
//       if (secondsRemaining.value <= 0) {
//         timer.cancel();
//         // Get.back();
//         _clearDataAndExit();
//       }
//     });
//   }

//   static Future<void> _clearDataAndExit() async {
//     await storage.deleteAll();
//     await box.erase();
//     exit(0); // Exit the app
//     print('exit');
//   }
// }

// class DeviceInfoPlus {
//   static List<Map<String, dynamic>> deviceDataList = [];

//   static Future<List<Map<String, dynamic>>> getDeviceInfo() async {
//     final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

//     try {
//       if (Platform.isAndroid) {
//         AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
//         Map<String, dynamic> deviceData = {
//           'platform': 'Android',
//           'brand': androidInfo.brand,
//           'model': androidInfo.model,
//           'androidId': androidInfo.device,
//           'versionRelease': androidInfo.version.release,
//           'sdkVersion': androidInfo.version.sdkInt,
//           'manufacturer': androidInfo.manufacturer,
//           'isPhysicalDevice': androidInfo.isPhysicalDevice,
//           'serialNumber': androidInfo.serialNumber,
//           'fingerprint': androidInfo.fingerprint,
//           'type': androidInfo.type,
//           'data': androidInfo.data,
//           'version': androidInfo.version,
//           'tags': androidInfo.tags,
//           'display': androidInfo.display,
//         };
//         deviceDataList.add(deviceData);
//       } else if (Platform.isIOS) {
//         IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
//         Map<String, dynamic> deviceData = {
//           'brand': 'Apple',
//           'model': iosInfo.model,
//           'systemName': iosInfo.systemName,
//           'systemVersion': iosInfo.systemVersion,
//           'utsname': iosInfo.utsname,
//           'isPhysicalDevice': iosInfo.isPhysicalDevice,
//           'identifierForVendor': iosInfo.identifierForVendor,
//           'name': iosInfo.name,
//           'localizedModel': iosInfo.localizedModel,
//         };
//         deviceDataList.add(deviceData);
//       } else if (Platform.isMacOS) {
//         MacOsDeviceInfo macInfo = await deviceInfoPlugin.macOsInfo;
//         Map<String, dynamic> deviceData = {
//           'platform': 'macOS',
//           'model': macInfo.model,
//           'version': macInfo.systemGUID,
//         };
//         deviceDataList.add(deviceData);
//       } else if (Platform.isWindows) {
//         WindowsDeviceInfo windowsInfo = await deviceInfoPlugin.windowsInfo;
//         Map<String, dynamic> deviceData = {
//           'platform': 'Windows',
//           'manufacturer': windowsInfo.computerName,
//           'version': windowsInfo.majorVersion,
//           'deviceId': windowsInfo.deviceId,
//           'userName': windowsInfo.userName,
//           'productName': windowsInfo.productName,
//           'installDate': windowsInfo.installDate,
//           'productId': windowsInfo.productId,
//           'numberOfCores': windowsInfo.numberOfCores,
//           'systemMemoryInMegabytes': windowsInfo.systemMemoryInMegabytes,
//         };
//         deviceDataList.add(deviceData);
//       } else if (Platform.isLinux) {
//         LinuxDeviceInfo linuxInfo = await deviceInfoPlugin.linuxInfo;
//         Map<String, dynamic> deviceData = {
//           'platform': 'Linux',
//           'manufacturer': linuxInfo.name,
//           'version': linuxInfo.version,
//         };
//         deviceDataList.add(deviceData);
//       }
//     } catch (e) {
//     }

//     return deviceDataList;
//   }

//   // Method to print all device data
//   static void printDeviceInfo() {
//     for (Map<String, dynamic> deviceData in deviceDataList) {
//           'Version: ${deviceData['version'] ?? deviceData['versionRelease'] ?? 'N/A'}');
//     }
//   }
// }
