/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
export const validateURL = (str: string): boolean => {
  let url;

  try {
    url = new URL(str);
  } catch (ignoredErr) {
    return false;
  }

  return !!url.protocol;
};

export const isEqual = (obj1: unknown, obj2: unknown): boolean => {
  // In this case we really accepting any types of arguments
  // TODO: Replace isEqual usage from components/shared/utils with this one

  const getType = (obj: unknown): string => {
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
  };

  const areArraysEqual = () => {
    if (obj1.length !== obj2.length) {
      return false;
    }

    for (let i = 0; i < obj1.length; i++) {
      if (!isEqual(obj1[i], obj2[i])) {
        return false;
      }
    }

    return true;
  };

  const areObjectsEqual = () => {
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
      return false;
    }

    for (const key in obj1) {
      if (Object.prototype.hasOwnProperty.call(obj1, key)) {
        if (!isEqual(obj1[key], obj2[key])) {
          return false;
        }
      }
    }

    return true;
  };

  const areFunctionsEqual = () => {
    return obj1.toString() === obj2.toString();
  };

  const arePrimativesEqual = () => {
    return obj1 === obj2;
  };

  const type = getType(obj1);

  if (type !== getType(obj2)) {
    return false;
  }

  if (type === 'array') {
    return areArraysEqual();
  }

  if (type === 'object') {
    return areObjectsEqual();
  }

  if (type === 'function') {
    return areFunctionsEqual();
  }

  return arePrimativesEqual();
};
