import {
	addFilter,
} from '@wordpress/hooks'

const getGoogleFontUrl = (url: string, id: string, config: Record<string, any>): string => {

	if(config.source !== 'googleFonts') {
		return url
	}

	const {
		font,
		variants = [],
	} = config

	if(!font) {
		return url
	}

	/**
	 * Transform
	 *   ['400', 'italic', '700', '900', '300italic']
	 * to
	 *   `:ital,wght@0,400;0,700;0,900;1,300;1,400`
	 */
	let variantsQueryString = ''
	if(variants.length > 0) {

		const variantsCollection = variants.reduce((acc: Record<string, [boolean, boolean]>, cur: string) => {
			const isItalic = cur.indexOf('italic') !== -1
			const variant = parseInt(cur === 'italic' ? '400' : cur.replaceAll('italic', ''))
			if(isNaN(variant)) {
				return acc
			}
			const key = variant.toString()
			acc[key] = acc[key] || [false, false]
			if(isItalic) {
				acc[key][1] = true
			} else {
				acc[key][0] = true
			}
			return acc
		}, {} as Record<string, [boolean, boolean]>)

		/**
		 * E.g.: `{'500': [true, false], '300': [true, true]}, '400': [false, true]}` -> `{'300': [true, true], '400': [false, true]}, '500': [true, false]}`
		 */
		const sortedVariantsCollection = Object.keys(variantsCollection).sort().reduce((acc, cur) => {
			acc[cur] = variantsCollection[cur]
			return acc
		}, {} as Record<string, [boolean, boolean]>)

		const variantsQueries = [
			...Object.keys(sortedVariantsCollection).map(variant => {
				const value = sortedVariantsCollection[variant]
				return value[0] ? `0,${variant}` : ''
			}).filter(v => v),
			...Object.keys(sortedVariantsCollection).map(variant => {
				const value = sortedVariantsCollection[variant]
				return value[1] ? `1,${variant}` : ''
			}).filter(v => v),
		]

		variantsQueryString = `:ital,wght@${variantsQueries.join(';')}`
	}

	return `https://fonts.googleapis.com/css2?family=${font.replaceAll(' ', '+')}${variantsQueryString}&display=swap`
}

export default () => {
	addFilter('ska.blocks.getFontUrl', 'ska-blocks/google-font/url', getGoogleFontUrl)
}
