import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:watermanagement/settings.dart';


class FireBaseCore {
  static String messageTokenEntity = "watermanagement_supplier";
  static final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
  static FirebaseFirestore firestoredb = FirebaseFirestore.instance;
  static CollectionReference messageTokenCollection = FirebaseFirestore.instance.collection(messageTokenEntity);
  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  static Map<String, dynamic> deviceData={};
  static String fcmToken = "";
  static String deviceId = "";
  static String spKeyReference="FCM_TOKEN";
  static bool _initialized = false;

  static Future<void> init() async {
    if (!_initialized) {
      // For iOS request permission first.
      firebaseMessaging.requestPermission();

      // For testing purposes print the Firebase Messaging token
       String? token = await FirebaseMessaging.instance.getToken();
       print("FirebaseMessaging token: $token");

      _initialized = true;
    }
  }

  static Future<void> checkFcmTokenInFireStoreDbWithdeviceId() async {
    await readDeviceInfo();
    await AppSettings.saveData("DEVICE_ID", deviceId, 'STRING');
    if(await AppSettings.getData(spKeyReference, 'STRING')==""){
      FirebaseFirestore.instance
          .collection(messageTokenEntity)
          .doc(deviceId)
          .get()
          .then((DocumentSnapshot documentSnapshot) async {

        if (documentSnapshot.exists) {
          Map<String, dynamic> dbRow = documentSnapshot.data() as Map<String, dynamic>;;
        //  (snapshot.data as DocumentSnapshot)['username']
          await AppSettings.saveData(spKeyReference,dbRow['_fcmToken'], 'STRING');
          AppSettings.fcmId=await AppSettings.getData('FCM_TOKEN', 'STRING');
          print('Document exists on the database');
        }
        else {
          await addDeviceFcmTokenToFireStoreDb();
        }
      }).catchError((error) {
        print("checkFcmTokenInFireStoreDbWithdeviceId failed $error");
      });
    }
  }

  static Future<void> updateWithUserInfo(Map<String,dynamic> input) async {
    await readDeviceInfo();
    try {
      messageTokenCollection.doc(deviceId).update(input).catchError((error) {
        print("Failed to add user: $error");
      });
    } catch (e) {
      print(e);
    }
  }

  static Future<void> createFcmToken() async {
    //fcmToken = (await firebaseMessaging.getToken())!;
    fcmToken = (await firebaseMessaging.getToken())!;
  }

  static Future<void> addDeviceFcmTokenToFireStoreDb() async {
    await readDeviceInfo();
    await createFcmToken();

    deviceData['_fcmToken'] = fcmToken;
    await AppSettings.saveData(spKeyReference, fcmToken, 'STRING');
    await AppSettings.saveData("DEVICE_ID", deviceId, 'STRING');
    AppSettings.fcmId=await AppSettings.getData('FCM_TOKEN', 'STRING');
    // Call the users CollectionReference to add a new user
    try {
      return messageTokenCollection.doc(deviceId).set(deviceData).then((value) {
        print("Device information store in fcm");
      }).catchError((error) {
        print("Failed to add user: $error");
      });
    } catch (e) {
      print(e);
    }
  }

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

  static Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    deviceId = build.androidId.toString();
    return deviceData = <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': 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,
      'id': 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,
      'deviceId': build.androidId,
      'systemFeatures': build.systemFeatures,
    };
  }

  static Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
    //deviceId = data.;
    return deviceData = <String, dynamic>{
      'name': data.name,
      'systemName': data.systemName,
      'systemVersion': data.systemVersion,
      '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,
    };
  }
}
