// ignore_for_file: use_build_context_synchronously, equal_keys_in_map

import 'dart:async';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:dart_ipify/dart_ipify.dart';

class DeviceInfo extends GetxController {
  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  DateTime _dateTime = DateTime.now();
  DateTime get dateTime => _dateTime;
  final List<Map<String, Object?>> _deviceInfo = [];
  List<Map<String, Object?>> get deviceInfo => _deviceInfo;

  DeviceInfo();
  Future<Map<String, String>> getDeviceInfo(
    // BuildContext context,
    String pageUrl,
    String? previousPageUrl,
  ) async {
    _dateTime = DateTime.now();
    final mediaQueryData =
        MediaQueryData.fromWindow(WidgetsBinding.instance.window);
    final size = mediaQueryData.size;
    var deviceInfo = await initPlatformState();
    // final ipv4 = await Ipify.ipv4();
    // final ipv6 = await Ipify.ipv64();
    String? token;
    if (Firebase.apps.isNotEmpty) {
      token = await FirebaseMessaging.instance.getToken();
    } 
    var mapData = {
      'token': token.toString(),
      'screenResolution': "${size.width} X ${size.height}",
      'platform': deviceInfo["platform"].toString(),
      'modelName': deviceInfo["model"].toString(),
      'version': deviceInfo["version"].toString(),
      'manufacturer': deviceInfo["manufacturer"].toString(),
      'isPhysicalDevice': deviceInfo["isPhysicalDevice"].toString(),
      // "ipv4": ipv4.toString(),
      // "ipv6": ipv6.toString(),
      "deviceId":deviceInfo["deviceId"].toString(),
      'visitedAt': _dateTime.toString(),
      'pageUrl': pageUrl.toString(),
      'previousPageUrl': previousPageUrl.toString(),
      // 'duration': null,
      // 'existedAt': null,
    };

    _deviceInfo.add(mapData);
    print(mapData);
    return mapData;
  }

  static initPlatformState() async {
    var deviceData = <String, dynamic>{};
    try {
      if (kIsWeb) {
        deviceData = _readWebBrowserInfo(await deviceInfoPlugin.webBrowserInfo);
      } else {
        if (Platform.isAndroid) {
          deviceData =
              _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
        } else if (Platform.isIOS) {
          deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo);
        }
      }
    } on PlatformException {
      deviceData = <String, dynamic>{
        'Error:': 'Failed to get platform version.'
      };
    }
    return deviceData;
  }

  static Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    return <String, dynamic>{
      "platform": "Android",
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      // 'version.release': build.version.release,
      'version': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'deviceId': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
      'androidId': build.id,
      'systemFeatures': build.systemFeatures,
    };
  }

  static Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
    return <String, dynamic>{
      "platform": "IOS",
      'name': data.name,
      'systemName': data.systemName,
      // 'systemVersion': data.systemVersion,
      'version': data.systemVersion,
      'manufacturer': "Apple",
      'model': data.model,
      'localizedModel': data.localizedModel,
      'deviceId': data.identifierForVendor,
      'isPhysicalDevice': data.isPhysicalDevice,
      'utsname.sysname:': data.utsname.sysname,
      'utsname.nodename:': data.utsname.nodename,
      'utsname.release:': data.utsname.release,
      'utsname.version:': data.utsname.version,
      'utsname.machine:': data.utsname.machine,
    };
  }

  static Map<String, dynamic> _readWebBrowserInfo(WebBrowserInfo data) {
    return <String, dynamic>{
      "platform": "Web",
      'isPhysicalDevice': true,
      'model': describeEnum(data.browserName),
      'appCodeName': data.appCodeName,
      'appName': data.appName,
      'manufacturer': data.appName,
      // 'appVersion': data.appVersion,
      'version': data.appVersion,
      'deviceMemory': data.deviceMemory,
      'language': data.language,
      'languages': data.languages,
      'platform': data.platform,
      'product': data.product,
      'productSub': data.productSub,
      'userAgent': data.userAgent,
      'vendor': data.vendor,
      'vendorSub': data.vendorSub,
      'hardwareConcurrency': data.hardwareConcurrency,
      'maxTouchPoints': data.maxTouchPoints,
    };
  }
}
