import type gradientParser from 'gradient-parser';
import type { GradientAST } from './types';

export function serializeGradientColor( {
	type,
	value,
}: gradientParser.ColorStop ) {
	if ( type === 'literal' ) {
		return value;
	}
	if ( type === 'hex' ) {
		return `#${ value }`;
	}
	if ( type === 'var' ) {
		return `var(${ value })`;
	}
	if ( type === 'hsl' ) {
		const [ hue, saturation, lightness ] = value;
		return `hsl(${ hue },${ saturation }%,${ lightness }%)`;
	}
	if ( type === 'hsla' ) {
		const [ hue, saturation, lightness, alpha = '1' ] = value;
		return `hsla(${ hue },${ saturation }%,${ lightness }%,${ alpha })`;
	}
	return `${ type }(${ value.join( ',' ) })`;
}

export function serializeGradientPosition(
	position: gradientParser.ColorStop[ 'length' ]
) {
	if ( ! position ) {
		return '';
	}
	const { value, type } = position;
	if ( type === 'calc' ) {
		return `calc(${ value })`;
	}
	return `${ value }${ type }`;
}

export function serializeGradientColorStop( {
	type,
	value,
	length,
}: gradientParser.ColorStop ) {
	return `${ serializeGradientColor( {
		type,
		value,
	} as gradientParser.ColorStop ) } ${ serializeGradientPosition( length ) }`;
}

export function serializeGradientOrientation(
	orientation: gradientParser.GradientNode[ 'orientation' ]
) {
	if (
		Array.isArray( orientation ) ||
		! orientation ||
		orientation.type !== 'angular'
	) {
		return;
	}
	return `${ orientation.value }${ orientation.unit }`;
}

export function serializeGradient( {
	type,
	colorInterpolation,
	orientation,
	colorStops,
}: GradientAST ) {
	// The color interpolation method shares the first argument with the
	// orientation, e.g. `linear-gradient(in oklch 160deg, …)`.
	const serializedOrientation = [
		colorInterpolation,
		serializeGradientOrientation( orientation ),
	]
		.filter( Boolean )
		.join( ' ' );
	const serializedColorStops = colorStops
		.sort( ( colorStop1, colorStop2 ) => {
			const getNumericStopValue = (
				colorStop: gradientParser.ColorStop
			) => {
				return colorStop?.length?.value === undefined
					? 0
					: parseInt( colorStop.length.value );
			};

			return (
				getNumericStopValue( colorStop1 ) -
				getNumericStopValue( colorStop2 )
			);
		} )
		.map( serializeGradientColorStop );
	return `${ type }(${ [ serializedOrientation, ...serializedColorStops ]
		.filter( Boolean )
		.join( ',' ) })`;
}
