import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:get_storage/get_storage.dart';
import '../../constant/box_name.dart';

class DeviceInfo {
  final String? manufacturer;
  final String? model;
  final String? deviceId;
  final String? osVersion;
  final String? platform;
  final String? deviceName;
  final bool? isPhysicalDevice;

  DeviceInfo({
    this.manufacturer,
    this.model,
    this.deviceId,
    this.osVersion,
    this.platform,
    this.deviceName,
    this.isPhysicalDevice,
  });

  Map<String, dynamic> toJson() => {
        'manufacturer': manufacturer,
        'model': model,
        'deviceId': deviceId,
        'osVersion': osVersion,
        'platform': platform,
        'deviceName': deviceName,
        'isPhysicalDevice': isPhysicalDevice,
      };
}

class DeviceController {
  final box = GetStorage();
  final _deviceInfo = DeviceInfoPlugin();

  Future<DeviceInfo> getDeviceInfo() async {
    if (Platform.isAndroid) {
      return await _getAndroidDeviceInfo();
    } else if (Platform.isIOS) {
      return await _getIosDeviceInfo();
    }
    throw UnsupportedError('Unsupported platform');
  }

  Future<DeviceInfo> _getAndroidDeviceInfo() async {
    final androidInfo = await _deviceInfo.androidInfo;
    final deviceInfo = DeviceInfo(
      manufacturer: androidInfo.manufacturer,
      model: androidInfo.model,
      deviceId: androidInfo.id,
      osVersion: androidInfo.version.release,
      platform: 'Android',
      deviceName: androidInfo.device,
      isPhysicalDevice: androidInfo.isPhysicalDevice,
    );

    box.write(BoxName.deviceInfo, deviceInfo.toJson());
    return deviceInfo;
  }

  Future<DeviceInfo> _getIosDeviceInfo() async {
    final iosInfo = await _deviceInfo.iosInfo;
    final deviceInfo = DeviceInfo(
      manufacturer: 'Apple',
      model: iosInfo.model,
      deviceId: iosInfo.identifierForVendor,
      osVersion: iosInfo.systemVersion,
      platform: 'iOS',
      deviceName: iosInfo.name,
      isPhysicalDevice: iosInfo.isPhysicalDevice,
    );

    box.write(BoxName.deviceInfo, deviceInfo.toJson());
    return deviceInfo;
  }
}
