import util from 'util';
import events from 'events';

let LightColorTemp = function () {
	this.lightOn = true;
	this.brightness = 0.5;
	this.colorTemp = 0.5;
	this.color = 0.5;
	this.saturation = 0.5;
	this.positionX = 99;
	this.positionY = 97.5;
	this.formatedColor = this.formatColor(this.positionY);
};

util.inherits(LightColorTemp, events.EventEmitter);

LightColorTemp.prototype.setLightOn = function (lightOn) {
	if (this.lightOn != lightOn) {
		this.lightOn = lightOn;
		this.emit('lightOn', lightOn);
	}
};

LightColorTemp.prototype.setBrightness = function (brightness) {
	if (this.brightness != brightness) {
		this.brightness = brightness;
		this.emit('brightness', brightness);
	}
};
LightColorTemp.prototype.formatBrightness = function (brightness) {
	return "" + parseInt((brightness)*100) + "%";
};

LightColorTemp.prototype.setColorTemp = function (colorTemp) {
	if (this.colorTemp != colorTemp) {
		this.colorTemp = colorTemp;
		this.emit('colorTemp', colorTemp);
	}
};

LightColorTemp.prototype.setColorTempPosition = function (x, y) {
	if (this.positionX != x) {
		this.positionX = x;
	}
	if (this.positionY != y) {
		this.positionY = y;
	}
};

LightColorTemp.prototype.formatColorTemp = function (colorTemp) {
	return "" + parseInt((5400 - 2700) * colorTemp + 2700) + "K";
};

LightColorTemp.prototype.setColor = function (y) {
	if (this.positionY != y) {
		this.formatedColor = this.formatColor(y);
	}
};

// hex to rgb
function hexToRgb(hex){
	var rgb = [];
	for(var i=1; i<7; i+=2){
		rgb.push(parseInt("0x" + hex.slice(i,i+2)));
	}
	return rgb;
}

// 计算渐变过渡色
function gradient (startColor,endColor,step,y){
	// 将 hex 转换为rgb
	var sColor = hexToRgb(startColor),
	eColor = hexToRgb(endColor);

	// 计算R\G\B每一步的差值
	var rStep = (eColor[0] - sColor[0]) / step;
	var gStep = (eColor[1] - sColor[1]) / step;
	var bStep = (eColor[2] - sColor[2]) / step;

	return [parseInt(rStep*y+sColor[0]),parseInt(gStep*y+sColor[1]),parseInt(bStep*y+sColor[2])];
}

LightColorTemp.prototype.formatColor = function (y) {
	if (y <= 0) {
		return `rgba(79, 168, 216, 1)`;
	} else if (y < 97.5) {
		let c = gradient('#4FA8D8', '#FFFFFF', 97.5, y);
		return `rgba(${c[0]},${c[1]},${c[2]},1)`;
	} else if (y == 97.5) {
		return `rgba(255,255,255,1)`;
	} else if (y > 97.5 && y < 195) {
		let c = gradient('#FFFFFF', '#F1C37A', 97.5, y - 97.7);
		return `rgba(${c[0]},${c[1]},${c[2]},1)`;
	} else if (y >= 195) {
		return `rgba(241, 195, 122, 1)`;
	}
};

export default new LightColorTemp;