import React from "react";
import { color } from "d3-color";
import { interpolateRgb } from "d3-interpolate";
import LiquidFillGauge from "react-liquid-gauge";


export function renderLabel(props, inputVal){
	const value = Math.round(parseFloat(inputVal));
	const radius = Math.min(props.height / 2, props.width / 2);
	const textPixels = (props.textSize * radius / 2);
	const valueStyle = {
		fontSize: textPixels
	};
	const percentStyle = {
		fontSize: textPixels * 0.6
	};

	return (
		<tspan>
			<tspan className="value" style={valueStyle}>{value}</tspan>
			<tspan style={percentStyle}>{props.percent}</tspan>
		</tspan>
	);
}


export function LiquidGauge(props){
	// tag, units, maxValue, label
	if (!props.tag){
		return <span className="liquidgauge-no-tags"></span>;
	}
	const tagValue = props.tag.value;
	const endColor = "#1F4788";
	const startColor = "#dc143c";
	
	const radius = 100;
	const interpolate = interpolateRgb(startColor, endColor);
	const fillColor = interpolate(tagValue / props.maxValue);
	const gradientStops = [
		{
			key: "0%",
			stopColor: color(fillColor).darker(0.5).toString(),
			stopOpacity: 1,
			offset: "0%"
		},
		{
			key: "50%",
			stopColor: fillColor,
			stopOpacity: 0.75,
			offset: "50%"
		},
		{
			key: "100%",
			stopColor: color(fillColor).brighter(0.5).toString(),
			stopOpacity: 0.5,
			offset: "100%"
		}
	];

	return (
		<div className={"col liquidfill lqdfill-" + props.tag.name} style={{textAlign: "center"}}>
			<h3>{props.label}</h3>
			<LiquidFillGauge
				style={{ margin: "0 auto" }}
				width={radius * 2}
				height={radius * 2}
				value={tagValue / props.maxValue * 100}
				percent={props.units}
				textSize={1}
				textOffsetX={0}
				textOffsetY={0}
				textRenderer={(props) => renderLabel(props, tagValue)}
				riseAnimation
				waveAnimation
				waveFrequency={3}
				waveAmplitude={2}
				gradient
				gradientStops={gradientStops}
				circleStyle={{fill: fillColor}}
				waveStyle={{fill: fillColor}}
				textStyle={{fill: color("#444").toString(), fontFamily: "Arial"}}
				waveTextStyle={{fill: color("#fff").toString(), fontFamily: "Arial"}}
			/>
		</div>
	);
}