import NumberUtil from "./NumberUtil";

export default class SortUtil {
  public static compareByBoolean<T>(
    object1: T,
    object2: T,
    key: keyof T,
  ): number {
    // eslint-disable-next-line @typescript-eslint/naming-convention
    const x = object1[key] as boolean;
    // eslint-disable-next-line @typescript-eslint/naming-convention
    const y = object2[key] as boolean;

    if (x === y) {
      return 0;
    }
    if (x) {
      return -1;
    }
    return 1;
  }

  public static compareByNumber<T>(
    object1: NonNullable<T> | undefined,
    object2: NonNullable<T> | undefined,
    key: keyof T,
  ): number {
    const value1 = object1?.[key] as number;
    const value2 = object2?.[key] as number;
    if (typeof value2 !== "number" || typeof value1 !== "number") {
      return 0;
    }
    return value1 > value2 ? 1 : -1;
  }

  public static compareByText<T>(object1: T, object2: T, key: keyof T): number {
    const value1 = (object1[key] as number | string).toString().toLowerCase();
    const value2 = (object2[key] as number | string).toString().toLowerCase();
    return value1.localeCompare(value2, "et-EE");
  }

  public static sortNumeric(list: number[]): number[] {
    return [...list].sort((a, b) => {
      if (typeof a !== "number" || typeof b !== "number") {
        return 0;
      }
      return a > b ? 1 : -1;
    });
  }

  public static compareByDate<T>(object1: T, object2: T, key: keyof T): number {
    const value1 = object1[key] as Date | string;
    const value2 = object2[key] as Date | string;
    const date1 = value1 instanceof Date ? value1 : new Date(value1);
    const date2 = value2 instanceof Date ? value2 : new Date(value2);
    if (NumberUtil.getValidNumber(date1.getTime()) === null) {
      return -1;
    }
    if (NumberUtil.getValidNumber(date2.getTime()) === null) {
      return 1;
    }
    return date1.getTime() - date2.getTime();
  }
}
