const hexToRgb = (hex: string) => {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function (_m, r, g, b) {
    return r + r + g + g + b + b;
  });

  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null;
};

interface IRGBValues {
  r: number;
  g: number;
  b: number;
}

const rgbToHex = ({ r, g, b }: IRGBValues) => {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};

export const getValuesFromRGBString = (rgb: string) => {
  const rgbValues = rgb.match(/\d+/g);
  if (rgbValues) {
    return {
      r: Number(rgbValues[0]),
      g: Number(rgbValues[1]),
      b: Number(rgbValues[2]),
      a: Number(rgbValues[3] || 1),
    };
  }
  return null;
};

export class ColorFormatter {
  public static rgbToHex = rgbToHex;
  public static hexToRgb = hexToRgb;
}
