/**
 * Helper function to transform a hex color into RGB numbers into a comma
 * separated string. Example: #FFFFFF will return '255,255,255'
 * @param hex color string in hex
 * @returns string in the format 'number, number, number'
 */
const toRgbValues = (hex: string): string => {
  if (typeof hex !== 'string') {
    console.warn(
      'attempted to convert a non-string hex color to an rgba string',
      hex
    );
    return hex;
  }
  if (hex.startsWith('rgba')) {
    // already an rgb string, let's just split it
    const rgba = hex.replace('rgba(', '').replace(')', '');
    // drop the alpha value
    return rgba.split(',').slice(0, 3).join(',');
  }

  if (hex.startsWith('rgb')) {
    // already an rgb string, let's just split it
    return hex.replace('rgb(', '').replace(')', '');
  }
  let hexColor = hex.replace(/^#/, '');
  if (hexColor.length === 3) {
    hexColor = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }
  const num = parseInt(hexColor, 16);
  return `${num >> 16}, ${(num >> 8) & 255}, ${num & 255}`;
};

/**
 * Create rgba with applied opacity for a hex color
 * @param hex color #hex
 * @param alpha number between 0 and 1
 * @returns the rgba value for that color
 */
export const setAlpha = (hex: string, alpha: number): string =>
  `rgba(${toRgbValues(hex)}, ${alpha})`;
