import R from 'ramda';
import React from 'react';
import { Seed } from 'react-seeds';

var hexColorRegex = /^[a-fA-F0-9]{3,6}$/;
var defaultSwatchSize = 32;

var parseColorValue = function parseColorValue() {
	var alpha = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
	return R.ifElse(R.test(hexColorRegex), function (value) {
		return '#' + value;
	}, R.pipe(R.split(/[,]?\s+/), R.cond([[R.propEq('length', 1), R.pipe(R.head, R.repeat(R.__, 3), R.append(alpha))], [R.propEq('length', 3), R.append(alpha)], [R.T, R.identity]]), R.join(','), function (value) {
		return 'rgba(' + value + ')';
	}));
};

var parseAlpha = R.pipe(parseFloat, R.when(isNaN, function () {}));

export var srgbItem = function srgbItem(value, alpha, minWidth, minHeight) {
	return React.createElement(Seed, {
		minWidth: minWidth,
		minHeight: minHeight,
		background: {
			color: parseColorValue(alpha)(value)
		}
	});
};

export var swatch = function swatch(tags, references, text, children, Element, resolveContent, _ref) {
	var elementFromText = _ref.elementFromText;

	var alpha = parseAlpha(resolveContent(tags.alpha));
	var minWidth = R.cond([[R.has('width'), R.pipe(R.prop('width'), resolveContent)], [R.has('size'), R.pipe(R.prop('size'), resolveContent)], [R.T, R.always(defaultSwatchSize)]])(tags);
	var minHeight = R.cond([[R.has('height'), R.pipe(R.prop('height'), resolveContent)], [R.has('size'), R.pipe(R.prop('size'), resolveContent)], [R.T, R.always(defaultSwatchSize)]])(tags);

	var content = resolveContent({ references: references, text: text });
	console.log('#swatch content', content);
	if (Array.isArray(content)) {
		children = content.map(elementFromText);
	}

	if (children.length > 0) {
		return React.createElement(
			Seed,
			{ row: true, wrap: true, alignItems: 'center' },
			Element.renderArray({ defaultTags: tags }, children)
		);
	} else if (R.is(String, content)) {
		return srgbItem(content, alpha, minWidth, minHeight);
	} else {
		return React.createElement('noscript', null);
	}
};

export var useWithFallback = function useWithFallback(fallback) {
	return R.cond([[R.has('swatch'), R.curry(swatch)], [R.T, fallback]]);
};