class StringUtils {
  static isNullOrEmpty(value: string | undefined): boolean {
    const valueTrimmed = value?.trim();
    return value === undefined || valueTrimmed === '';
  }

  static trimToNull(value: string | undefined): string | undefined {
    const valueTrimmed = value?.trim();
    return StringUtils.isNullOrEmpty(valueTrimmed) ? undefined : valueTrimmed;
  }

  static capitalize(type: string | undefined) {
    if (type === undefined) {
      return '';
    }
    return type.charAt(0).toUpperCase() + type.substring(1);
  }

  /**
   * Finds the first pattern in an array that matches a given URL.
   * Patterns can include a single wildcard '*' which matches any sequence of characters.
   *
   * @param patterns
   * @param urlToTest
   * @returns
   */
  static findMatchingPattern(patterns: string[], urlToTest: Location): string | undefined {
    if (!urlToTest) {
      return undefined;
    }

    for (const pattern of patterns) {
      // Test only if a pathname is present.
      if (urlToTest.pathname !== '/') {
        // Escape special regex characters in the pattern
        // This ensures that characters like '.', '+', '?', '(', etc., in the pattern are treated literally.
        const escapedPattern = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');

        // Replace the wildcard '*' with its regex equivalent '.*' (matches any character zero or more times)
        const regexPattern = escapedPattern.replace(/\*/g, '.*');

        const regex = new RegExp(`^${regexPattern}$`);
        if (regex.test(urlToTest.pathname)) {
          return pattern;
        }
      } else if (pattern.startsWith(urlToTest.hostname)) {
        return pattern;
      }
    }
    return undefined;
  }
}

export { StringUtils };
