import { DataFormat } from "select2";

export class Utils {
  // The DataFormat is unstable, one time we access the id directly, another time we have to use .id
  public static extractIdFromDataFormat(df: DataFormat): number {
    if (df == null) return null;
    return Number.isInteger(df) ? df as any : df.id;
  }

  public static hasDecimals(val: number): boolean {
    return val - Math.round(val) !== 0;
  }

  public static isNullOrEmpty(str: string): boolean {
    return str == null || str.trim().length == 0;
  }

  public static isNotEmpty(str: string): boolean {
    return false == this.isNullOrEmpty(str);
  }

  public static arrayHasDuplicates(array: Array<any>): boolean {
    return array.some((item, index) => array.indexOf(item) !== index);
  }

  private static bodyFromHTML(html: string): HTMLElement | { innerText: string, innerHTML: string } {
    if (html != null && typeof (html) == 'string' && (html.includes('html') || html.includes('body') || html.includes('head'))) {
      let str = html;
      if (str.includes("<head>")) {
        str = str.slice(str.lastIndexOf('</head>') + "</head>".length).trimStart();
      }
      return new DOMParser().parseFromString(str, 'text/html').body;
    }
    return { innerText: html, innerHTML: html };
  }

  /**
   * Returns the inner text of a variable if the variable is a string containing HTML
   * @param {string} html The string from which we want to extract the inner text
   * @return {string} Inner text if the given parameter is a string containing HTML. Otherwise, the original parameter value
   */
  public static innerTextFromHTML(html: string): string {
    return this.bodyFromHTML(html).innerText;
  }

  /**
  * Returns the inner HTML of a variable if the variable is a string containing HTML
  * @param {string} html The string from which we want to extract the inner HTML
  * @return {string} Inner HTML if the given parameter is a string containing HTML. Otherwise, the original parameter value
  */
  public static innerHTMLFromHTML(html: string): string {
    return this.bodyFromHTML(html).innerHTML;
  }
}