//TODO: Move to utils package
/**
 * @description Converts a hex value into an array of RGB values.
 *
 * @param {string} hex
 *
 * @return {*}
 */
export const hexToRGB = ( hex ) => {
	const hexArray = hex.replace( '#', '' ).match( /.{1,2}/g );
	return {
		R: parseInt( hexArray[ 0 ], 16 ),
		G: parseInt( hexArray[ 1 ], 16 ),
		B: parseInt( hexArray[ 2 ], 16 ),
	};
};

/**
 * @description Converts an RGB value into a hex value.
 *
 * @param {string} R
 * @param {string} G
 * @param {string} B
 *
 * @return {string}
 */
export const RGBtoHex = ( R, G, B ) => {
	const rgb = {
		R, G, B,
	};
	if ( R.length === 1 ) {
		rgb.R = '0' + rgb.R;
	}
	if ( G.length === 1 ) {
		rgb.G = '0' + rgb.G;
	}
	if ( B.length === 1 ) {
		rgb.B = '0' + rgb.B;
	}
	return `#${ rgb.R }${ rgb.G }${ rgb.B }`;
};

/**
 * @description Returns the inverted color of input hex.
 *
 * @param {string}  hex
 * @param {boolean} bw
 *
 * @return {string}
 */
export const invertColor = ( hex, bw = true ) => {
	const rgb = hexToRGB( hex );
	if ( bw ) {
		// https://stackoverflow.com/a/3943023/112731
		return ( ( rgb.R * 0.299 ) + ( rgb.G * 0.587 ) + ( rgb.B * 0.114 ) ) > 186 ? '#000000' : '#FFFFFF';
	}
	rgb.R = ( 255 - rgb.R ).toString( 16 );
	rgb.G = ( 255 - rgb.G ).toString( 16 );
	rgb.B = ( 255 - rgb.B ).toString( 16 );
	return RGBtoHex( rgb.R, rgb.G, rgb.B );
};
