// eslint-disable-next-line @typescript-eslint/no-var-requires
const ColorContrastChecker = require("color-contrast-checker");

const colorContrastChecker = new ColorContrastChecker();

export function hexToRgbA(hex: string, opacity: number) {
  if (hex === "" || !hex) return;
  let c: any;
  if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
    c = hex.substring(1).split("");
    if (c.length == 3) {
      c = [c[0], c[0], c[1], c[1], c[2], c[2]];
    }
    c = "0x" + c.join("");
    return (
      "rgba(" +
      [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(",") +
      `,${opacity})`
    );
  }

  return hex;
}

export function isValidColorContrast(
  backgroundColor?: string,
  typographyColor?: string
) {
  if (!backgroundColor || !typographyColor) return true;
  try {
    return colorContrastChecker.isLevelAA(backgroundColor, typographyColor, 14);
  } catch (ex) {
    return false;
  }
}

// https://gist.github.com/larryfox/1636338
export function detectLightOrDark(backgroundColor: string): "light" | "dark" {
  try {
    let a: any = backgroundColor;
    let r: any;
    let g: any;
    let b: any;
    let hsp = 0;
    if (a.match(/^rgb/)) {
      a = a.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
      r = a[1];
      g = a[2];
      b = a[3];
    } else {
      a = +(
        "0x" +
        a.slice(1).replace(
          // thanks to jed : http://gist.github.com/983661
          a.length < 5 && /./g,
          "$&$&"
        )
      );
      r = a >> 16;
      b = (a >> 8) & 255;
      g = a & 255;
    }

    hsp = Math.sqrt(
      // HSP equation from http://alienryderflex.com/hsp.html
      0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b)
    );
    if (hsp > 127.5) {
      return "light";
    } else {
      return "dark";
    }
  } catch {
    return "light";
  }
}
