import {
  Alert,
  Linking,
  PermissionsAndroid,
  ToastAndroid,
  Platform,
} from "react-native";
import React, { useCallback, useEffect, useRef, useState } from "react";
import Geolocation from "react-native-geolocation-service";

import Database from "../../../../Components/common/DAsyncStorage";
import { render } from "@testing-library/react-native";
import { View } from "react-native";
import DeviceInfo from "react-native-device-info";
import { UELogEvent } from "../common/libEventLog/UserExperior/LibUserExperior";
import { useFocusEffect } from "@react-navigation/core";
import { requestLocationPermission } from "./Permissions";
import { RESULTS } from "react-native-permissions";
import { NamedModal } from "react-native-digitcamera/src/common/GlobalModal";
import store from "react-native-digitcamera/src/redux/store";

const updateLocation = async (position) => {
  console.log("LocationHandler . updateLocation . position - ", position);
  await Database.update("PILocation", {
    lat: position?.coords?.latitude.toString().substring(0, 10),
    long: position?.coords?.longitude.toString().substring(0, 10),
  });
};

const updateLocationNA = async () => {
  try {
    await Database.update("PILocation", {
      lat: "NA",
      long: "NA",
    });
  } catch (error) {
    console.log(
      "LocationHandler . updateLocationNA . error -> ",
      error?.message
    );
  }
};

let permissionRequestCount = 1;

const watchLocation = async () => {
  await Database.update("PILocation", {
    lat: "NA",
    long: "NA",
  });
  let result = await requestLocationPermission();
  if (result === RESULTS.DENIED) {
    store.dispatch({
      type: "LOCATION_DENIED",
    });
    Alert.alert(
      "Location required!",
      "To smoothen your process we recommend you to enable device location.",
      [
        {
          text: "Ok",
          onPress: () => {
            console.log("Permission requested count  ", permissionRequestCount);
            if (permissionRequestCount < 2) {
              watchLocation();
              permissionRequestCount++;
            } else {
              store.dispatch({
                type: "LOCATION_BLOCKED",
              });
              store.dispatch({
                type: "GLOBAL_MODAL_SHOW",
                payload: NamedModal.OPEN_APP_SETTINGS,
              });
            }
          },
        },
      ]
    );
    return;
  } else if (result === RESULTS.GRANTED) {
    store.dispatch({
      type: "LOCATION_GRANTED",
    });
    const options = {
      accuracy: {
        android: "balanced",
        ios: "best",
      },
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 10000,
      distanceFilter: 50,
      forceRequestLocation: true,
      forceLocationManager: true,
      showLocationDialog: true,
    };

    DeviceInfo.isLocationEnabled().then((enable) => {
      if (!enable) {
        updateLocationNA();
        if (Platform.OS == "android") {
          const LocationEnabler =
            require("react-native-location-enabler").default;
          const {
            PRIORITIES: { BALANCED_POWER_ACCURACY },
            requestResolutionSettings,
          } = LocationEnabler;
          setTimeout(() => {
            requestResolutionSettings({
              priority: BALANCED_POWER_ACCURACY,
              alwaysShow: true, //
              needBle: false, //
            });
          }, 3000);
        }
      } else {
        Geolocation.getCurrentPosition(
          (position) => {
            updateLocation(position);
          },
          (error) => {
            updateLocationNA();
            UELogEvent("Geolocation.watchPosition error", {
              Position: JSON.stringify(error),
            });
            console.log("Location Error ", error.message);
          },
          options
        );
      }
    });

    return;
  } else if (result === RESULTS.BLOCKED || result === RESULTS.UNAVAILABLE) {
    store.dispatch({
      type: "LOCATION_BLOCKED",
    });
    store.dispatch({
      type: "GLOBAL_MODAL_SHOW",
      payload: NamedModal.OPEN_APP_SETTINGS,
    });
  }
};

export default function GetLocation() {
  useFocusEffect(
    useCallback(() => {
      watchLocation();
    }, [])
  );
  return null; // render nothing
}
