var groupArr = [];

function getGroupByRgid(rgid) {
    for (var i = 0; i < groupArr.length; i++) {
        if (groupArr[i].rgid === rgid) {
            return groupArr[i];
        }
    }

    return undefined;
}

function recalcAllGroupParams() {
    for (var i = 0; i < groupArr.length; i++) {
        mapLevelToPercent(groupArr[i]);
        mapSatToPercent(groupArr[i]);
    }
}

function copyGroup(dst, src) {
    if (src.name !== undefined) {
        dst.name = src.name;
    }

    if (src.pgid !== undefined) {
        dst.pgid = src.pgid;
    }

    if (src.rgid !== undefined) {
        dst.rgid = src.rgid;
    }

    if (src.updateId !== undefined) {
        dst.updateId = src.updateId;
    }

    if (src.isLocation !== undefined) {
        dst.isLocation = src.isLocation;
    }

    if (src.isSubGroup !== undefined) {
        dst.isSubGroup = src.isSubGroup;
    }

    if (src.on !== undefined) {
        dst.on = src.on;
    }

    if (src.hue !== undefined) {
        dst.hue = src.hue;
    }

    if (src.sat !== undefined) {
        dst.sat = src.sat;
    }

    if (src.satPercent !== undefined) {
        dst.satPercent = src.satPercent;
    }

    if (src.level !== undefined) {
        dst.level = src.level;
    }

    if (src.levelPercent !== undefined) {
        dst.levelPercent = src.levelPercent;
    }

}

function updateGroupUi(group) {
    var el = $('div.location[data-gid="' + group.id + '"]').each(function() {

    });
}

function lightToHtml(light, visible) {

	//dont display white channel of multi-devices
	var mac = light.uniqueid.substring(0,light.uniqueid.indexOf("-"));
	var multideviceWhiteChannel = false;
	var hascolor = (light.state.colormode === undefined) ? false : true;

	//if (config.config.rgbwdisplay === "1") {
		for (i in config.lights) {
			var mac2 = config.lights[i].uniqueid.substring(0,config.lights[i].uniqueid.indexOf("-"));
			var masterHasColor = (config.lights[i].state.colormode === undefined) ? false : true;
			if (mac == mac2 && light.id != config.lights[i].id && hascolor == false && masterHasColor == true) {

				multideviceWhiteChannel = true;
				// mark the other light as multidevice master
				config.lights[i].multideviceID = light.id;
				config.lights[i].multideviceUID = light.uniqueid;
				break;
			}
		}
	//}

	if (multideviceWhiteChannel == false) {
		mapLevelToPercent(light);

		var onOffClass = (light.state.on && light.state.reachable) ? "light_on " : "";
		if (light.state.on && light.state.effect == "colorloop" && light.state.reachable) {
			onOffClass = "light_colorloop ";
		}

		var visibleClass = (visible == "false") ? "hidden " : " ";

		var reachableClass = light.state.reachable ? " " : "not_reachable ";
		var txt = "";
		txt += "<tr class=\"" + reachableClass + visibleClass + "light_item\" data-lid=\"" + light.id + "\">";
		txt += "<td class=\"" + onOffClass + "onoff_button\" data-lid=\"" + light.id + "\"></td>";
		txt += "<td class=\"light_level\">" + light.levelPercent + "%</td>";
		txt += "<td class=\"name\">" + light.name + "</td>";
		txt += "<td class=\"edit_button\" style=\"background-position-y: 10px;\" data-lid=\"" + light.id + "\"></td>";
		txt += "</tr>";
		return txt;
	}
	return "";
}

function groupToHtml(group, lights) {

	if (group.apitype && group.apitype !== 'LightGroup')
		return '';

    var btnSize = isDesktop ? "" : "btn-large";
	var visible = null;
	if ((Modernizr.localstorage) && (localStorage.getItem("visible-" + group.id) != null) && (localStorage.getItem("visible-" + group.id) != undefined)) {
		visible = localStorage.getItem("visible-" + group.id);
	}
	var ind = (visible == "false") ? '<img src="img/plus.png" />' : '<img src="img/minus.png" />';
	if (group.lights.length == 0) {
		ind = "";
	}

	var groupDeviceType = "";
	var deviceIcon = "";
	var modelId = "";
	var lsensor = getSensorActive(group.id, "ZHALight");
	var psensor = getSensorActive(group.id, "ZHAPresence");

	if (config.sensors[group.devicemembership[0]] != undefined)
	{
		groupDeviceType = config.sensors[group.devicemembership[0]].type;
		if (groupDeviceType == "ZHASwitch") {

			modelId = config.sensors[group.devicemembership[0]].modelid || undefined;

			if (modelId === "RWL020" || modelId === "RWL021") {
				deviceIcon = "<img src=\"img/rwl_small.png\" style=\"margin-top:-3px;\"/> ";
			}
			else if (modelId === "Scene Switch") {
				deviceIcon = "<img src=\"img/zhaswitch3_small.png\" style=\"margin-top:-3px;\"/> ";
			}
			else if (modelId === "Lighting Switch") {
				deviceIcon = "<img src=\"img/zhaswitch2_small.png\" style=\"margin-top:-3px;\"/> ";
			}
		}
	}

    var txt = '<div class="location span6" style="margin-left:0px;" data-gid="' + group.id + '">';

    txt += '<table><thead><th></th><th></th><th></th><th></th></thead>';
    txt += '<tbody>';
    txt += '<tr>';
    txt += '<td colspan="3" class="locName lightFont"><span class="visible-indicator">' + ind + '</span><span class="LightSensor" data-gid="' + group.id + '">' + lsensor + '</span></span><span class="PresenceSensor" data-gid="' + group.id + '">' + psensor + '</span>' + deviceIcon + group.name + '</td>';
    txt += '<td class="edit_button edit_group" data-gid="' + group.id + '"></td>';
    txt += '</tr>';

	var sortArr = [];

	if (group.lightsequence != undefined && group.lightsequence.length > 0) {
		sortArr = group.lightsequence;
	}

	for (var so = 0; so < sortArr.length; so++) {
		for (var i = 0; i < group.lights.length; i++) {
			var light = lights[group.lights[i]];
			if (light !== undefined && light.id === sortArr[so]) {
				txt += lightToHtml(light, visible);
				break;
			}
		}
	}

	// append lights that where not sorted yet
		for (var i = 0; i < group.lights.length; i++) {
			var light = lights[group.lights[i]];
			if (light !== undefined && (!_.contains(sortArr, light.id))) {
				txt += lightToHtml(light, visible);
			}
		}

    txt += '</tbody>';
    txt += '</table>';

    txt += '<span class="btn ' + btnSize + ' actionButton onButton" data-gid="' + group.id + '" data-action="on">On</span>';
    txt += '<span class="btn ' + btnSize + ' actionButton offButton" data-gid="' + group.id + '" data-action="off">Off</span>';
	var sceneName = "";
	if (modelId == "Scene Switch" || (modelId == "Lighting Switch" && config.sensors[group.devicemembership[0]].mode == 1)) { // use modelid
		sceneName = "Scene 1";
		for (s in group.scenes) {
			if (group.scenes[s].id == "1") {
				sceneName = group.scenes[s].name;
				break;
			}
		}
		txt += '<span style="background-image: linear-gradient(to bottom, #8e8e8e, #5d5d5d);background-color:#5d5d5d;" class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="1" data-action="callscene">' + sceneName + '</span>';

		if (modelId == "Scene Switch") {
			sceneName = "Scene 2";
			for (s in group.scenes) {
				if (group.scenes[s].id == "2") {
					sceneName = group.scenes[s].name;
					break;
				}
			}
			txt += '<span style="background-image: linear-gradient(to bottom, #8e8e8e, #5d5d5d);background-color:#5d5d5d;" class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="2" data-action="callscene">' + sceneName + '</span>';

			sceneName = "Scene 3";
			for (s in group.scenes) {
				if (group.scenes[s].id == "3") {
					sceneName = group.scenes[s].name;
					break;
				}
			}
			txt += '<span style="background-image: linear-gradient(to bottom, #8e8e8e, #5d5d5d);background-color:#5d5d5d;" class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="3" data-action="callscene">' + sceneName + '</span>';
		}
		sceneName = "Scene 4";
		if (modelId == "Lighting Switch") {
			sceneName = "Scene 2";
		}
		for (s in group.scenes) {
			if (group.scenes[s].id == "4") {
				sceneName = group.scenes[s].name;
				break;
			}
		}
		txt += '<span style="background-image: linear-gradient(to bottom, #8e8e8e, #5d5d5d);background-color:#5d5d5d;" class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="4" data-action="callscene">' + sceneName + '</span>';
	}

    if (group.scenes !== undefined) {
        for (var i = 0; i < group.scenes.length; i++) {
			if (modelId == "Scene Switch") { // use modelid
				if (i > 3) {
					var scene = group.scenes[i];
					txt += '<span class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="' + scene.id + '" data-action="callscene">' + scene.name + '</span>';
				}
			} else if (modelId == "Lighting Switch" && config.sensors[group.devicemembership[0]].mode == 1) {
				if (i > 1) {
					var scene = group.scenes[i];
					txt += '<span class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="' + scene.id + '" data-action="callscene">' + scene.name + '</span>';
				}
			} else {
				var scene = group.scenes[i];
				txt += '<span class="btn ' + btnSize + ' actionButton" data-gid="' + group.id + '" data-sid="' + scene.id + '" data-action="callscene">' + scene.name + '</span>';
			}
        }
    }

    txt += '<span class="btn ' + btnSize + ' actionButton editScenesButton" data-gid="' + group.id + '">...</span>';
    txt += '</div>';
    return txt;
}

function addGroupToUi(group, lights, rowtxt) {
	group.type = TYPE_GROUP;
    group.hasColor = true;
    group.state = group.action;

    rowtxt += groupToHtml(group, lights);
    groupArr.push(group);

    return rowtxt;
}

/**
* Check if this group has an associated sensor with rules and check if this rules are active or inactive.
*/
function getSensorActive(groupId, wantedSensorType) {

	var sensorType = 0; // 0 = other; 1 = light sensor; 2 = presence sensor
	var enabledRulefound = false;

	for (r in config.rules) {
		var sid = "";
		var actions = config.rules[r].actions;
		var conditions = config.rules[r].conditions;
		for (c in conditions) {
			var addr = conditions[c].address;
			sid = addr.substring(addr.indexOf("/sensors/")+9, addr.indexOf("/state"))
			break;
		}
		if (config.sensors[sid] != undefined && config.sensors[sid].type.indexOf(wantedSensorType) !== -1) {
			if (config.sensors[sid].type.indexOf("ZHALight") !== -1 && config.sensors[sid].config.reachable != false) {
				sensorType = 1;
			} else if (config.sensors[sid].type == "ZHAPresence" && config.sensors[sid].config.reachable != false) {
				sensorType = 2;
			}
			for (a in actions) {
				var addr = actions[a].address;
				if (addr.indexOf("groups/" + groupId + "/") != -1) {
					enabledRulefound = true;
					if (config.rules[r].status === "enabled") {
						// return enabled sensor
						if (sensorType === 1) {
							return "&#9728; "; // Light
						} else if (sensorType === 2) {
							return "&#9852; "; // Presence
						}
					}
				}
			}
		}
	}
	// return disabled sensor
	if (enabledRulefound === true && sensorType === 1) {
		return "&#9788; "; // Light disabled
	} else if (enabledRulefound === true && sensorType === 2) {
		return "&#9853; "; // Presence disabled
	}
	// return no sensor
	return "";
}

/**
 * Helper to adjust the size of the name field to not exceed the table size.
 */
function adjustLightNames() {
    $('.location').each(function(index) {
        if (index > 0) {
            var maxwidth = $(this).innerWidth() - 180;
            $('.light_item td:nth-child(3)').each(function(index) {
                $(this).css('max-width', maxwidth + 'px');
            });
        }
    });
}

// build and show device list ui
function checkGroups(groups) {
    var groupCount = 0;

    // compatibility to to older API
    for (var g in groups) {
        groups[g].id = g;
        groups[g].rgid = g;
        if (typeof(groups[g].type) === 'string')
            groups[g].apitype = groups[g].type;
        groupCount++;
    }

    // check for group updates
    for (var i = 0; i < groupArr.length; i++) {
        var g = groupArr[i];
        var found = false;

        for (var id in groups) {
            var g2 = groups[id];

            if (g.id === g2.id) {
                mapLevelToPercent(g2);
                mapSatToPercent(g2);
                copyGroup(g, g2);
                found = true;
                break;
            }
        }
    }

    var k = 0;
    var left = "";
	var right = "";

	left += '<div class="column-fluid" style="float:left;">';
	right += '<div class="column-fluid" style="float:right">';

	for (var i = 0; i < groupssequenceleft.length; i++) {
		for (var id in groups) {
			if (id === groupssequenceleft[i]) {
				var gnew  = groups[id];
				var gnum = $('div.location[data-gid="' + gnew.id + '"]').length;

				if (gnum === 0 && config.groups[id].hidden === false) {
					left += addGroupToUi(gnew, config.lights, "");
				}
				break;
			}
		}
	}
	for (var i = 0; i < groupssequenceright.length; i++) {
		for (var id in groups) {
			if (id === groupssequenceright[i]) {
				var gnew  = groups[id];
				var gnum = $('div.location[data-gid="' + gnew.id + '"]').length;

				if (gnum === 0 && config.groups[id].hidden === false) {
					right += addGroupToUi(gnew, config.lights, "");
				}
				break;
			}
		}
	}
	// append groups which were not sorted yet
		for (var id in groups) {
			if (!_.contains(groupssequenceleft, id) && !_.contains(groupssequenceright, id)) {
				var gnew  = groups[id];
				var gnum = $('div.location[data-gid="' + gnew.id + '"]').length;

				if ((k % 2) === 0) {
					if (gnum === 0 && config.groups[id].hidden === false) {
						left += addGroupToUi(gnew, config.lights, "");
					}
				}

				if ((k % 2) === 1) {
					if (gnum === 0 && config.groups[id].hidden === false) {
						right += addGroupToUi(gnew, config.lights, "");
					}
				}
				k++;
			}
		}
	//}
	left += '</div>';
	right += '</div>';

    pageLightList.innerHTML += left+right;

    adjustLightNames();
}
