'use strict';
const css = require('css');
const cssToReactNative = require('css-to-react-native').default;
const { remToPx, isUtilitySupported } = require('./util');
const getNotAbleParseStyles = require('./getNotAbleParseStyles');

const getStyles = rule => {
	const styles = rule.declarations
		.filter(({property, value}) => {
			// Skip line-height utilities without units
			if (property === 'line-height' && !value.endsWith('rem')) {
				return false;
			}

			return true;
		})
		.map(({property, value}) => {
			if (value.endsWith('rem') || value.endsWith('em')) {
				return [property, remToPx(value)];
			}

			return [property, value];
		});
	return cssToReactNative(styles);
};

module.exports = source => {
	const {stylesheet} = css.parse(source);

	// Mapping of Tailwind class names to React Native styles
	const styles = {};

	for (const rule of stylesheet.rules) {
		if (rule.type === 'rule') {
			for (const selector of rule.selectors) {
				const utility = selector.replace(/^\./, '').replace('\\/', '/');

				if (isUtilitySupported(utility, rule)) {
					styles[utility] = getStyles(rule);
				}
			}
		}
	}

	// Additional styles that we're not able to parse correctly automatically
	const notAbleParseStyles = getNotAbleParseStyles()
	styles.underline = notAbleParseStyles.underline
	styles['line-through'] = notAbleParseStyles['line-through']
	styles['no-underline'] = notAbleParseStyles['no-underline']
	
	return styles;
};
