import { Alert, NativeModules, DeviceEventEmitter, View } from "react-native";
import React from "react";
import { useSelector } from "react-redux";
import reactotron from "reactotron-react-native";
import RNFetchBlob from "rn-fetch-blob";
import { SELFSURVEYSERVICE_DOCUMENT_URL } from "../Api/ApiUrls";
import { async } from "validate.js";
import Database from "../../../../Components/common/Database";
import DeviceInfo from "react-native-device-info";
const IMEI = require("react-native-imei");

let realm = Database.getRealm();
var PILocation = realm.objects("PILocation");
var currentLatitude = PILocation[0]?.lat;
var currentLongitude = PILocation[0]?.long;

var mSensorManager = NativeModules.SensorManager;
var accelerometerData = [];
var gyroscopeData = [];
var magnetometerData = [];
var pedometerData = [];
var compassData = [];
var SensorDataInfo;
var deviceName;
var MAC;
var IP;
var IMEInumber;
var APILevel;
// capcture sensor data
export function startCapturingSensorData(int) {
  //Accelerometer
  mSensorManager.startAccelerometer(100); // To start the accelerometer with a minimum delay of 100ms between events.
  DeviceEventEmitter.addListener("Accelerometer", function (data) {
    (data.timestamp = new Date().getTime()), accelerometerData.push(data);
  });

  //Gyroscope
  mSensorManager.startGyroscope(100);
  DeviceEventEmitter.addListener("Gyroscope", function (data) {
    (data.timestamp = new Date().getTime()), gyroscopeData.push(data);
  });

  //Magnetometer
  mSensorManager.startMagnetometer(100);
  DeviceEventEmitter.addListener("Magnetometer", function (data) {
    (data.timestamp = new Date().getTime()), magnetometerData.push(data);
  });

  //Pedometer
  mSensorManager.startStepCounter(1000);
  DeviceEventEmitter.addListener("StepCounter", function (data) {
    (data.timestamp = new Date().getTime()), pedometerData.push(data);
  });
}
// genrate sensor data
export function genrateSensorFile(
  activityId,
  activityTypeId,
  licensePlateNumber,
  quoteNumber,
  sensorImageDetails
) {
  const date = new Date().getDate();
  const month = new Date().getMonth() + 1;
  const year = new Date().getFullYear();

  //Time calulation for the display on preciew Screen
  const hour = new Date().getHours();
  const minute = new Date().getMinutes();
  const seconds = new Date().getSeconds();

  SensorDataInfo = {
    activity_id: activityId,
    activity_type: activityTypeId,
    date_time:
      year +
      " " +
      month +
      " " +
      date +
      "  " +
      hour +
      ":" +
      minute +
      ":" +
      seconds,
    imageDetails: sensorImageDetails,
    policy_no: quoteNumber,
    reg_no: licensePlateNumber,
    sensor_data: {
      accelerometers: accelerometerData,
      compass: compassData,
      gyroscope: gyroscopeData,
      magnetometers: magnetometerData,
      millis: new Date().getTime(),
      pedometer: pedometerData,
    },
  };
  const filename = activityId + "_" + "Sensor.json";
  const destPath = RNFetchBlob.fs.dirs.DownloadDir + "/" + filename;
  RNFetchBlob.fs
    .writeFile(destPath, JSON.stringify(SensorDataInfo, null, "  "), "utf8")
    .then(async (data) => {
      await uploadSensorData("file://" + destPath, activityId, activityTypeId);
      RNFetchBlob.fs.exists(destPath).then((data) => {
        console.log("IS EXIST  >> ", data);
      });
    })
    .catch((e) => {
      console.log("ERROR    ", e);
    });

  // stop capture data once all photo completed
  mSensorManager.stopAccelerometer();
  mSensorManager.stopStepCounter();
  mSensorManager.stopMagnetometer();
  mSensorManager.stopGyroscope();
}

const getDeviceInfo = () => {
  try {
    DeviceInfo.getDeviceName().then((DeviceName) => {
      deviceName = DeviceName;
    });

    DeviceInfo.getMacAddress().then((mac) => {
      MAC = mac;
    });
    DeviceInfo.getIpAddress().then((ip) => {
      IP = ip;
    });

    DeviceInfo.getApiLevel().then((apiLevel) => {
      APILevel = apiLevel;
      if (apiLevel > 28) {
        DeviceInfo.getAndroidId().then((androidId) => {
          IMEInumber = androidId;
        });
      } else {
        IMEI.getImei().then((imeiList) => {
          IMEInumber = imeiList;
        });
      }
    });
  } catch (error) {
    console.log("Error in SensorData.js getDeviceInfo() ", error);
  }
};

//upload sensor data file
const uploadSensorData = async (uri, activityId, activityTypeId) => {
  try {
    await getDeviceInfo();
    console.log("@@@@@@@@@@@@@@@@@", deviceName, APILevel, IP, IMEInumber, MAC);
    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    console.log("Sensor TO BE UPLOADED > > >   ", uri);
    const handleProgress = (event) => {
      reactotron.log(Math.round(event.loaded * 100) / event.total);
    };
    const documentUploadData = {
      activityId: activityId,
      geoLocation: {
        isBlocked: "false",
        deviceName: deviceName,
        latitude: currentLatitude,
        longitude: currentLongitude,
        operatingSystem: APILevel,
        timezone: "Asia/Kolkata",
        deviceTime: null,
        ipAddress: IP,
        deviceIMEI: IMEInumber,
        macAddress: MAC,
      },
      isLast: "false",
      isLastDocument: "false",
    };

    formData.append("file", {
      uri: uri,
      type: "image/jpeg",
      fileName: activityId + "_" + "Sensor",
      name: activityId + "_" + "Sensor.json",
    });
    formData.append("documentData", JSON.stringify(documentUploadData));

    xhr.upload.addEventListener("progress", handleProgress);
    xhr.addEventListener("load", () => {
      reactotron.log("Sensor file   >>>   100 ", xhr.response);
      console.log("Sensor Data Uploaded");
      console.log("Sensor Data STATUS  > > >", xhr.response);
    });
    xhr.open("POST", SELFSURVEYSERVICE_DOCUMENT_URL);
    xhr.setRequestHeader(
      "Accept",
      "*/*",
      "Content-Type",
      "multipart/form-data"
    );
    xhr.send(formData);
  } catch (error) {
    console.log("Error in Upload Sensor Data ", error);
  }
};
