export function Name() { return "DRGB LED Controller"; }
export function VendorId() { return 0x2023; }
export function ProductId() { return 0x1208; }
export function Publisher() { return "YanZhi"; }
export function Size() { return [1, 1]; }
export function DefaultPosition(){ return [160, 100]; }
export function DefaultScale(){ return 1.0; }
export function Type() { return "Hid"; }
export function SubdeviceController(){ return true; }
export function DefaultComponentBrand() { return "CompGen"; }

export function ControllableParameters() {
	return [
		{"property":"seek", "group":"lighting", "label":"呼吸定位设备", "type":"boolean", "default":"true", "tooltip":"启用后，未添加模型的接口单色呼吸，根据接口颜色定位设备,设置完成后推荐关闭!推荐关闭！"},
		{"property":"LightingMode", "group":"lighting", "label":"模式", "type":"combobox", "values":["Canvas", "Forced"], "default":"Canvas", "tooltip":"Canvas：画布模式__Forced：单色模式!"},
		{"property":"forcedColor", "group":"lighting", "label":"Forced Color", "min":"0", "max":"360", "type":"color", "default":"#FF0000"},
		{"property":"ColorCompression_enable", "group":"", "label":"启用颜色压缩（减少光谱并提高帧速率）", "type":"boolean", "default":"true", "tooltip":"单个设备大于20可以开启，且单个设备灯珠越多效果越明显好"},
		{"property":"HWL_enable", "group":"", "label":"启用硬件照明更改", "type":"boolean", "default":"false", "tooltip":"启用硬件照明更改3秒后生效，修改完成请一定关闭!修改完成请一定关闭!修改完成请一定关闭!"},
		{"property":"HWL_effectMode", "group":"", "label":"硬件照明效果", "type":"combobox", "values":["Rainbow Wave", "Color Shift","Color Wave ","Solid Color","Visor","Marquee", "Sequential"], "default":"Rainbow Wave", "tooltip":"Rainbow Wave彩虹通道/Color Shift色彩偏差/Color Wave色波/Solid Color纯色/Visor晴朗/Marquee跑马灯/Sequential序列"},
		{"property":"HWL_effectSpeed", "group":"", "label":"硬件照明效果的速度", "step":"1", "type":"number", "min":"0", "max":"2", "default":"1", "tooltip":"硬件照明灯效的速度!"},
		{"property":"HWL_direction", "group":"", "label":"硬件照明效果方向", "type":"combobox", "values":["Front", "After"], "default":"Front", "tooltip":"Front正向__After反向!"},
		{"property":"HWL_random", "group":"", "label":"硬件照明效果颜色随机", "type":"boolean", "default":"true", "tooltip":"硬件照明灯效颜色随机（彩虹灯效无效）!"},
		{"property":"HWL_color", "group":"", "label":"选择纯色和呼吸效果", "min":"0", "max":"360", "type":"color", "default":"#FF0000", "tooltip":"硬件照明灯效颜色1!"},
		{"property":"HWL_colorB", "group":"", "label":"选择纯色2", "min":"0", "max":"360", "type":"color", "default":"#0000FF", "tooltip":"硬件照明灯效颜色2!"},
		{"property":"HWL_mode", "group":"", "label":"切换控制盒模式", "type":"combobox", "values":["DRGB", "AURA", "ICUE8", "ICUE16", "ICUE24", "ICUE30", "ICUEBUT"], "default":"DRGB", "tooltip":"切换控制盒模式DRGB__华硕AURA__ICUE8/16/24/30识别为commander__ICUEBUT恢复拨码调整模式!"},
		
			];
}

export function DeviceMessages() {
	return [
		{property: "Hardware Ligthing", message:"支持无软件的硬件照明效果更改", tooltip: "启用硬件照明更改3秒后生效，但请不要频繁更改!"},
	];
}

const DeviceMaxLedLimit = 800;
const ChannelArray =
[
	["Channel A1", 288],
	["Channel A2", 288],
	["Channel A3", 288],
	["Channel A4", 288],
	["Channel A5", 288],
	["Channel A6", 288],
	["Channel A7", 288],
	["Channel A8", 288],	
];

function SetupChannels() {
	device.SetLedLimit(DeviceMaxLedLimit);

	for(let i = 0; i < ChannelArray.length; i++) {
		device.addChannel(ChannelArray[i][0], ChannelArray[i][1]);
	}
}

//const PluginVersion = "0.9.212";

const vKeyNames = [];
const vKeyPositions = [];
const MaxLedsInPacket = 20;

let lastHWLchange = 0;
let HWLupdateRequested = false;

export function LedNames() {
	return vKeyNames;
}

export function LedPositions() {
	return vKeyPositions;
}

export function Initialize() {
	SetupChannels();
	requestFirmwareVersion();
}

function compareFirmwareVersion() {
	const firmwarePacket = device.read([0x00],  5 );
	const FirmwareVersion = firmwarePacket[2] + "." + firmwarePacket[3] + "." + firmwarePacket[4];
	device.log("SignalRGB Firmware version: " + FirmwareVersion);
/*	device.log("SignalRGB Plugin version:   " + PluginVersion);

	if(FirmwareVersion !== PluginVersion) {
		device.log("Firmware <-> Plugin version mismatch! Make sure to use matching versions!");
		device.notify(`Firmware ${FirmwareVersion} <-> Plugin ${PluginVersion} version mismatch!`, `Make sure to use matching versions!`, 0);
	}*/
}

function requestFirmwareVersion() {
	const packet = [ 0x00, 0x02 ];
	device.write(packet, 65);
	compareFirmwareVersion();
}

export function Render() {
	for(let i = 0; i < ChannelArray.length; i++) {
		SendChannel(i);
	}
	if(HWL_enable){
	if(HWLupdateRequested == true) {
		const currentTime = Date.now();

		if(currentTime - lastHWLchange >= 3000) {
			updateHWLsettings();
		}
	}
	}
}

export function Shutdown() {
	for(let i = 0; i < ChannelArray.length; i++) {
		SendChannel(i, true);
	}
}

function SendChannel(Channel, shutdown = false) {
	const componentChannel = device.channel(ChannelArray[Channel][0]);
	let ChannelLedCount = componentChannel.ledCount > ChannelArray[Channel][1] ? ChannelArray[Channel][1] : componentChannel.ledCount;
	let RGBData = [];

	const multiplier = ColorCompression_enable ? 2 : 1;
	const compressedRGB = [];
	if(!ChannelLedCount){
		if(seek){
		ChannelLedCount = 40;
		const pulseColor = device.getChannelPulseColor(ChannelArray[Channel][0]);
		RGBData = device.createColorArray(pulseColor, ChannelLedCount, "Inline");
		}
	} else if(LightingMode === "Forced") {
		RGBData = device.createColorArray(forcedColor, ChannelLedCount, "Inline");
	} 

	else {
		RGBData = componentChannel.getColors("Inline");
	}

	if(ColorCompression_enable) {
		for(let runCount = 0; runCount < ChannelLedCount * 3 / multiplier; runCount++) {
			compressedRGB[(runCount*3)] = (((RGBData[(runCount*6)] & 0xFF) >> 4) | ((((RGBData[(runCount*6)+1] & 0xFF) >> 4) & 0xFF) << 4));
			compressedRGB[(runCount*3)+1] = (((RGBData[(runCount*6)+2] & 0xFF) >> 4) | ((((RGBData[(runCount*6)+3] & 0xFF) >> 4) & 0xFF) << 4));
			compressedRGB[(runCount*3)+2] = (((RGBData[(runCount*6)+4] & 0xFF) >> 4) | ((((RGBData[(runCount*6)+5] & 0xFF) >> 4) & 0xFF) << 4));
		}
	}
	const compressionenable = ColorCompression_enable == true ? 0xAA : 0xBB;
	const NumPackets = Math.ceil(ChannelLedCount / MaxLedsInPacket / multiplier);
	for(let CurrPacket = 1; CurrPacket <= NumPackets; CurrPacket++) {
		let packet = [0x00, CurrPacket, NumPackets, Channel, compressionenable];
		packet = packet.concat(ColorCompression_enable ? compressedRGB.splice(0, 60) : RGBData.splice(0, 60));
		device.write(packet, 65);
	}
}

function hexToRgb(hex) {
	const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
	const colors = [];
	colors[0] = parseInt(result[1], 16);
	colors[1] = parseInt(result[2], 16);
	colors[2] = parseInt(result[3], 16);

	return colors;
}

export function onColorCompression_enableChanged(){ HWL_setting_updated(); }	
export function onHWL_effectModeChanged(){ HWL_setting_updated(); }
export function onHWL_effectSpeedChanged(){ HWL_setting_updated(); }
export function onHWL_directionChanged(){ HWL_setting_updated(); }
export function onHWL_randomChanged(){ HWL_setting_updated(); }
export function onHWL_colorChanged(){ HWL_setting_updated(); }
export function onHWL_colorBChanged(){ HWL_setting_updated(); }

export function onHWL_modeChanged(){ HWL_setting_mode(); }

function HWL_setting_mode() {
	let hwlmode;		
	if(HWL_mode == "DRGB") { hwlmode = 0x01; } else if(HWL_mode == "AURA") { hwlmode = 0x02; } else if(HWL_mode == "ICUE8") { hwlmode = 0x08; } else if(HWL_mode == "ICUE16") { hwlmode = 0x10; } else if(HWL_mode == "ICUE24") { hwlmode = 0x18; } else if(HWL_mode == "ICUE30") { hwlmode = 0x1E; }else if(HWL_mode == "ICUEBUT") { hwlmode = 0xF0; } 
	const packet = [0x00, 0x45, 0x35, hwlmode];
	device.write(packet, 65);
}

function HWL_setting_updated() {
	lastHWLchange = Date.now();
	HWLupdateRequested = true;
}

function updateHWLsettings() {
	
		HWLupdateRequested = false;

		let hwleffectMode;	
		let hwldirection;	
		if(HWL_effectMode == "Rainbow Wave") { hwleffectMode = 0; } else if(HWL_effectMode == "Color Shift") { hwleffectMode = 1; } else if(HWL_effectMode == "Color Wave") { hwleffectMode = 3; } else if(HWL_effectMode == "Solid Color") { hwleffectMode = 4; } else if(HWL_effectMode == "Visor") { hwleffectMode = 6; } else if(HWL_effectMode == "Marquee") { hwleffectMode = 7; } else if(HWL_effectMode == "Sequential") { hwleffectMode = 9; }
		if(HWL_direction == "Front") { hwldirection = 1; } else if(HWL_direction == "After") { hwldirection = 0; } 

		const random = HWL_random == true ? 0x01 : 0x00;
		const hwlcolor = hexToRgb(HWL_color);
		const hwlcolorB = hexToRgb(HWL_colorB);
		const packet = [0x00, 0x35, 0x00, 0x00, 0x00, hwleffectMode, HWL_effectSpeed, hwldirection, random, 0x00, hwlcolor[0], hwlcolor[1], hwlcolor[2], hwlcolorB[0], hwlcolorB[1], hwlcolorB[2]];
		device.write(packet, 65);
	
}

export function Validate(endpoint) {
	return endpoint.interface === 0 || endpoint.interface === 2;
}

export function ImageUrl() {
	return "https://gitee.com/drgb-controller/drgb/raw/master/Image/DRGBV3.png"
}