export default class TextUtil {
  public static isEmpty(string?: unknown | null): boolean {
    return typeof string !== "string" || string.trim().length === 0;
  }

  public static trim(value?: string | null): string | undefined {
    return value?.replace(/\s/g, "");
  }

  public static sanitizeUnescapedQuotesAndLoadJsonStr<T>(s: string): T {
    let jsStr = s;
    let prevPos = -1;
    let currPos = 0;

    while (currPos > prevPos) {
      // after while check, move marker before we overwrite it
      prevPos = currPos;

      try {
        return JSON.parse(jsStr) as T;
      } catch (err) {
        // TypeScript doesn't have a direct equivalent to Python's JSONDecodeError
        // So we need to extract the position from the error message
        if (err instanceof SyntaxError) {
          // Extract position from error message
          const match = /at position (\d+)/.exec(err.message);
          if (match) {
            currPos = Number.parseInt(match[1]!, 10);

            if (currPos <= prevPos) {
              // previous change didn't make progress, so error
              throw err;
            }

            // find the previous " before currPos
            const prevQuoteIndex = jsStr.lastIndexOf('"', currPos);
            if (prevQuoteIndex !== -1) {
              // escape it to \"
              jsStr = `${jsStr.slice(0, prevQuoteIndex)}\\${jsStr.slice(
                prevQuoteIndex,
              )}`;
            }
          } else {
            throw err; // Can't find position in error message
          }
        } else {
          throw err; // Not a JSON syntax error
        }
      }
    }

    throw new Error(
      "Failed to parse JSON after attempting to fix unescaped quotes",
    );
  }
}
