import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:service/constant/box_name.dart';
import 'package:service/controller/functions/encrypt_decrypt.dart';
import '../../main.dart';
import '../../print.dart';

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

    try {
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        deviceData = androidInfo.toMap();
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
        deviceData = iosInfo.toMap();
      } else {
        throw UnsupportedError('Unsupported platform');
      }

      final String deviceId = Platform.isAndroid
          ? deviceData['id'] ??
              deviceData['androidId'] ??
              deviceData['fingerprint'] ??
              'unknown'
          : deviceData['identifierForVendor'] ?? 'unknown';

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

      Log.print('DeviceId: $deviceId');
      Log.print('DeviceModel: $deviceModel');

      final String fingerprint =
          EncryptionHelper.instance.encryptData('${deviceId}_$deviceModel');

      Log.print('Generated Fingerprint: $fingerprint');
      box.write(BoxName.fingerPrint, fingerprint);
      return (fingerprint);
    } catch (e) {
      Log.print('Error generating device fingerprint: $e');
      return '';
    }
  }
}
