/**
 * A Network listener that listens for internet state and updates the state to redux
 * Please do NOT code things NOT related to NET INFO, so that this file is kept isolated
 * and only concerns with Network
 *
 *  [USAGE]
 *
 *  How to access internet state app wide.
 *
 *  const network = useSelector((state) => state.network);
 *  const { isInternetReachable } = network;
 *
 *  isInternetReachable - default - undefined
 *  isInternetReachable - on internet access - true
 *  isInternetReachable - on no internet access - false
 *
 *
 *  [IMPORTANT]
 *  by default NETINFO returns isInternetReachable as false
 *  which was causing issue like poping up a offline modal even if there is internet
 *  or running any statements which should only run when the internet reachability is checked and found false
 *
 */

import { View, Text } from "react-native";
import React, { useEffect } from "react";
import { useNetInfo } from "@react-native-community/netinfo";
import { useDispatch } from "react-redux";
import { measureConnectionSpeed } from "react-native-network-bandwith-speed";
import { dlog } from "./DLogger";
import { UELogEvent } from "react-native-digitcamera/src/common/libEventLog/UserExperior/LibUserExperior";

/**
 * nlLog()
 * arguments - contains parameters passed into the function
 * arguments[0] - should always be a event passed to analytics tool
 * */

function nlLog() {
  dlog("[GLOBALS] [NET INFO] ", ...arguments);
  UELogEvent(`${arguments[0]}`);
}

export const getInternetState = async () => {
  const DataSpeed = await measureConnectionSpeed();
  var kbps = DataSpeed?.speed * 1024;
  nlLog("Dataspeed : ", kbps);
  UELogEvent("Dataspeed", {
    speed: `${kbps} kbps`,
  });
  if (kbps < 100) {
    return true;
  }
  return false;
};

const NetworkListener = () => {
  const netInfo = useNetInfo();
  const disptach = useDispatch();
  useEffect(async () => {
    if (netInfo.isInternetReachable) {
      const isLowInternet = await getInternetState();
      if (isLowInternet) {
        disptach({
          type: "NETWORK_DISCONNECTED",
        });
        nlLog("[NO INTERNET ACCESS (SPEED LESS THAN 100 KBPS)] [OFFLINE MODE]");
      } else {
        disptach({
          type: "NETWORK_CONNECTED",
        });
        nlLog("[INTERNET ACCESS] [ONLINE MODE]");
      }
    } else if (netInfo.isInternetReachable === false) {
      disptach({
        type: "NETWORK_DISCONNECTED",
      });
      nlLog("[NO INTERNET ACCESS] [OFFLINE MODE]");
    }
  }, [netInfo.isInternetReachable]);
  return null;
};

export default NetworkListener;
