var channelId;
import RNFS from "react-native-fs";
import notifee from "@notifee/react-native";
import { Alert } from "react-native";

const getChannelId = async () => {
  if (!channelId) {
    channelId = await notifee.createChannel({
      id: "default",
      name: "Default Channel",
    });
  }
  return channelId;
};

const sendNotification = async (data) => {
  var channel = await getChannelId();
  var notifyData = data;
  notifyData.android.channelId = channel;
  await notifee.displayNotification(notifyData);
};

const changeToInteger = (value, withCurrency = false) => {
  let result = "0";
  if (value)
    result = Number(value.toString().replace(/INR/g, ""))
      .toLocaleString("en-US", { maximumFractionDigits: 0 })
      .replace(/(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/g, "$1,");
  const currencyText = withCurrency ? "₹ " : "";
  return currencyText + result;
};

const roundAndAddComma = (value) => {
  if (value) {
    value = Math.round(Number(value.replace(/,/g, "")));
    if (value) value = changeToInteger(value);
  }
  return value;
};

const removeComma = (value) => {
  if (!value) {
    return "";
  }
  let tempValue = value;
  while (tempValue.indexOf(",") !== -1) {
    tempValue = tempValue.replace(",", "");
  }
  return tempValue;
};

const capitalize = (s) => {
  if (typeof s !== "string") return "";
  const array = s.split(" ");
  const arrayWithoutEmptyString = array.filter((i) => i !== "");
  const arrayWithAllCapitalized = arrayWithoutEmptyString.map((i) => {
    i = i.toLowerCase();
    return i.charAt(0).toUpperCase() + i.slice(1);
  });
  let finalString = arrayWithAllCapitalized.toString();
  while (finalString.indexOf(",") >= 0) {
    finalString = finalString.replace(",", " ");
  }
  return finalString;
};

const changeToIntegerINR = (value) => {
  let result = "0";
  if (value) {
    let x = value.toString();
    var lastThree = x.substring(x.length - 3);
    var otherNumbers = x.substring(0, x.length - 3);
    if (otherNumbers != "") lastThree = "," + lastThree;
    result = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
  }

  return result;
};

const truncate = (value, length) => {
  if (value.length >= length) {
    return value.split("").slice(0, length).join("") + "....";
  } else return value;
};

const currencyString = (
  amount,
  withCurrency = true,
  numberOfFractionDigit = 1
) => {
  const NUMBER_LACK = 100000;
  const NUMBER_CRORE = 10000000;
  if (typeof amount === "string" && amount.indexOf("INR") !== -1) {
    amount = amount.replace("INR", "");
  }
  amount = Number(amount);
  const currencyText = withCurrency ? "₹ " : "";
  if (amount >= 0 || amount < 0) {
    if (amount >= NUMBER_CRORE) {
      return (
        currencyText +
        (amount / NUMBER_CRORE).toFixed(numberOfFractionDigit) +
        " Cr"
      );
    } else if (amount >= NUMBER_LACK) {
      return (
        currencyText +
        (amount / NUMBER_LACK).toFixed(numberOfFractionDigit) +
        " L"
      );
    } else if (amount < 0) {
      if (amount * -1 >= NUMBER_CRORE) {
        return (
          currencyText +
          (amount / NUMBER_CRORE).toFixed(numberOfFractionDigit) +
          " Cr"
        );
      } else if (amount * -1 >= NUMBER_LACK) {
        return (
          currencyText +
          (amount / NUMBER_LACK).toFixed(numberOfFractionDigit) +
          " L"
        );
      } else {
        return currencyText + changeToInteger(amount.toFixed());
      }
    }
    // else if (amount > 10000) return '₹ ' + (amount / 1000).toFixed(1) + ' Thousand'
    else {
      return currencyText + changeToInteger(amount.toFixed());
    }
  } else {
    return "...";
  }
};
const chars =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const atob = (input) => {
  let str = input.replace(/=+$/, "");
  let output = "";

  if (str.length % 4 == 1) {
    throw new Error(
      "'atob' failed: The string to be decoded is not correctly encoded."
    );
  }
  for (
    let bc = 0, bs = 0, buffer, i = 0;
    (buffer = str.charAt(i++));
    ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)
      ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))
      : 0
  ) {
    buffer = chars.indexOf(buffer);
  }

  return output;
};

//getting minimum value from array of object
export const getMinimumOfArray = (data, key, keyFormater = (key) => key) => {
  const minimum = data?.reduce(
    (min, p) => (keyFormater(p[key]) < min ? keyFormater(p[key]) : min),
    keyFormater(data?.[0]?.[key])
  );
  return minimum;
};
//getting minimum value from array of object
export const getMaximumOfArray = (data, key, keyFormater = (key) => key) => {
  const maximum = data?.reduce(
    (max, p) => (keyFormater(p[key]) > max ? keyFormater(p[key]) : max),
    keyFormater(data?.[0]?.[key])
  );
  return maximum;
};

export const currencyToNumber = (currencyString) => {
  if (!currencyString) return 0;
  return Number(currencyString?.toString().replace("INR", ""));
};

const getMime = (ext) => {
  const mimes = {
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    png: "image/png",
    svg: "image/svg+xml",
    pdf: "application/pdf",
  };

  ext = ext.toLowerCase();
  if (mimes?.[ext]) return mimes[ext];
  else return mimes.pdf;
};

export const wait = async (milliseconds = 500) => {
  console.log("##WAITING... ", new Date());
  return await new Promise((resolve) => {
    const timer = setTimeout(() => {
      clearTimeout(timer);
      console.log("###WAIT OVER. ", new Date());
      resolve(true);
    }, milliseconds);
  });
};

const downloadFileToDevice = async ({
  url,
  filename,
  destPath,
  notification = true,
}) => {
  console.log("@@@@@", url);
  try {
    var num = 1,
      pathFileName = filename;
    const downloadFolder = RNFS.DownloadDirectoryPath;
    var prefix = destPath
      ? destPath.replace("/" + filename, "")
      : downloadFolder;
    var filePath = prefix + "/" + filename;
    // Renaming if File exists
    while ((await RNFS.exists(filePath)) === true) {
      var ext = filename.split(".").pop();
      pathFileName = filename.replace(`.${ext}`, "") + `(${num})` + `.${ext}`;
      filePath = prefix + "/" + pathFileName;
      num += 1;
    }
    // Download with Notification
    await RNFS.downloadFile({
      fromUrl: url,
      toFile: filePath,
      progress: async (res) => {
        if (notification) {
          await sendNotification({
            title: "Downloading " + pathFileName,
            id: pathFileName,
            android: {
              progress: {
                max: 10,
                current: Math.round(res.bytesWritten / res.contentLength),
              },
              pressAction: {
                launchActivity: "default",
                id: "default",
              },
              onlyAlertOnce: true,
              smallIcon: "download_notification",
            },
          });
        }
      },
      progressDivider: 10,
    }).promise;
    if (notification) {
      await sendNotification({
        title: "Download Completed",
        id: pathFileName,
        body: pathFileName,
        android: {
          smallIcon: "download_notification",
          pressAction: {
            launchActivity: "default",
            id: "default",
          },
        },
        data: { path: filePath },
      });
    }
    return {
      path: () => {
        return filePath;
      },
      base64: async () => {
        var data = await RNFS.readFile(filePath, "base64");
        return data;
      },
    };
  } catch (e) {
    console.log("Download Error ---->", e);
  }
};

const hideHeaderInWebView = `let Nodes = document.querySelectorAll(".header-wrap,.header-top,header-section-wrapper,header");
for(let i=0; i<Nodes.length; i++){    
    Nodes[i].style.display = "none";
};
    true;`;

const onErrorhandler = (event) => {
  Alert.alert(
    "",
    "Oops! Something went wrong!. \nPlease try again later",
    [{ text: "OK", onPress: () => {} }],
    { cancelable: false }
  );
};

const getUTMSource = (url) => {
  return url + "?utm_source=digit_mobileapp";
};

export {
  changeToInteger,
  capitalize,
  currencyString,
  removeComma,
  roundAndAddComma,
  changeToIntegerINR,
  truncate,
  downloadFileToDevice,
  hideHeaderInWebView,
  onErrorhandler,
  getUTMSource,
};
