var app = app || {};

function displayGroups(config) {

    var k = 0;
    var txtLeft = '<div id="leftColumn" class="span6">';
    var txtRight = '<div id="rightColumn" class="span6">';

	for (var i = 0; i < groupssequenceleft.length; i++) {
		for (var id in config.groups) {
			if (id === groupssequenceleft[i]) {
				var g = config.groups[id];
				debugger
				var scenes = 'scenes';
				if (g.scenes.length == 1) {
					scenes = 'scene';
				}

				if (g.type !== 'LightGroup')
					continue;

				var countLights = 0;
				for (l in g.lights) {
					var modelId = config.lights[g.lights[l]].modelid;
					if (modelId != "FLS-PP3 White" /*|| config.config.rgbwdisplay == "2"*/) {
						countLights++;
					}
				}
				var deviceType = "";
				var deviceModelId = "";
				var deviceIcon = "";

				if (config.groups[id].hidden === false) {
					if (config.sensors[g.devicemembership[0]] != undefined) {
						deviceType = config.sensors[g.devicemembership[0]].type;

						if (deviceType === "ZHASwitch") {
							deviceModelId = config.sensors[g.devicemembership[0]].modelid;

							deviceIcon = "<img src=\"img/zhaswitch2_small.png\" style=\"margin-top:-10px;;\"/>";
							if (deviceModelId == "RWL021") {
								deviceIcon = "<img src=\"img/rwl_small.png\" style=\"margin-top:-10px;;\"/> ";
							}
							if (deviceModelId == "Scene Switch") {
								deviceIcon = "<img src=\"img/zhaswitch3_small.png\" style=\"margin-top:-10px;;\"/> ";
							}
						}
					}

					var txt = '<div class="groupElement" id="'+ id +'"><h4>' + deviceIcon + " " + g.name + ' <small>' + countLights + ' lights, ' + g.scenes.length + ' ' + scenes + '</small></h4>';
					txt += '<div class="btn-toolbar">';
					if (localStorage.getItem("de-gw-swVersion") != undefined) {
						var swVersion = localStorage.getItem("de-gw-swVersion");
						txt += '<a class="btn" href="edit_group_members.html?group=' + id + '&v=' + swVersion + '">Edit Members</a>';
					} else {
						txt += '<a class="btn" href="edit_group_members.html?group=' + id + '">Edit Members</a>';
					}

					if (deviceType != "ZHASwitch") {
						txt += '<a class="btn btn-danger" href="#" onclick="showDeleteGroupModal(' + id + ');return false;">Delete</a>';
					}

					txt += '</div><br /></div>';

					txtLeft += txt;
					break;
				}
			}
		}
	}

	for (var i = 0; i < groupssequenceright.length; i++) {
		for (var id in config.groups) {
			if (id === groupssequenceright[i]) {
				var g = config.groups[id];
				var scenes = 'scenes';
				if (g.scenes.length == 1) {
					scenes = 'scene';
				}

				if (g.type !== 'LightGroup')
					continue;

				var countLights = 0;
				for (l in g.lights) {
					var modelId = config.lights[g.lights[l]].modelid;
					if (modelId != "FLS-PP3 White" /*|| config.config.rgbwdisplay == "2"*/) {
						countLights++;
					}
				}
				var deviceType = "";
				var deviceModelId = "";
				var deviceIcon = "";

				if (config.groups[id].hidden === false) {
					if (config.sensors[g.devicemembership[0]] != undefined) {

						deviceType = config.sensors[g.devicemembership[0]].type;

						if (deviceType === "ZHASwitch") {
							deviceModelId = config.sensors[g.devicemembership[0]].modelid;

							deviceIcon = "<img src=\"img/zhaswitch2_small.png\" style=\"margin-top:-10px;;\"/>";
							if (deviceModelId == "RWL021") {
								deviceIcon = "<img src=\"img/rwl_small.png\" style=\"margin-top:-10px;;\"/> ";
							}
							if (deviceModelId == "Scene Switch") {
								deviceIcon = "<img src=\"img/zhaswitch3_small.png\" style=\"margin-top:-10px;;\"/> ";
							}
						}
					}

					var txt = '<div class="groupElement" id="'+ id +'"><h4>' + deviceIcon + " " + g.name + ' <small>' + countLights + ' lights, ' + g.scenes.length + ' ' + scenes + '</small></h4>';
					txt += '<div class="btn-toolbar">';
					if (localStorage.getItem("de-gw-swVersion") != undefined) {
						var swVersion = localStorage.getItem("de-gw-swVersion");
						txt += '<a class="btn" href="edit_group_members.html?group=' + id + '&v=' + swVersion + '">Edit Members</a>';
					} else {
						txt += '<a class="btn" href="edit_group_members.html?group=' + id + '">Edit Members</a>';
					}

					if (deviceType != "ZHASwitch") {
						txt += '<a class="btn btn-danger" href="#" onclick="showDeleteGroupModal(' + id + ');return false;">Delete</a>';
					}

					txt += '</div><br /></div>';

					txtRight += txt;
					break;
				}
			}
		}
	}

	// append groups which were not sorted yet
		for (var id in config.groups) {
			if (!_.contains(groupssequenceleft, id) && !_.contains(groupssequenceright, id)) {
				var g = config.groups[id];
				var scenes = 'scenes';
				if (g.scenes.length == 1) {
					scenes = 'scene';
				}

				if (g.type !== 'LightGroup')
					continue;

				var countLights = 0;
				for (l in g.lights) {
					var modelId = config.lights[g.lights[l]].modelid;
					if (modelId != "FLS-PP3 White" /*|| config.config.rgbwdisplay == "2"*/) {
						countLights++;
					}
				}
				var deviceType = "";
				var deviceModelId = "";
				var deviceIcon = "";

				if (config.groups[id].hidden === false) {
					if (config.sensors[g.devicemembership[0]] != undefined) {

						deviceType = config.sensors[g.devicemembership[0]].type;

						if (deviceType === "ZHASwitch") {
							deviceModelId = config.sensors[g.devicemembership[0]].modelid;

							deviceIcon = "<img src=\"img/zhaswitch2_small.png\" style=\"margin-top:-10px;;\"/>";
							if (deviceModelId == "RWL021") {
								deviceIcon = "<img src=\"img/rwl_small.png\" style=\"margin-top:-10px;;\"/> ";
							}
							if (deviceModelId == "Scene Switch") {
								deviceIcon = "<img src=\"img/zhaswitch3_small.png\" style=\"margin-top:-10px;;\"/> ";
							}
						}
					}

					var txt = '<div class="groupElement" id="'+ id +'"><h4>' + deviceIcon + " " + g.name + ' <small>' + countLights + ' lights, ' + g.scenes.length + ' ' + scenes + '</small></h4>';
					txt += '<div class="btn-toolbar">';
					if (localStorage.getItem("de-gw-swVersion") != undefined) {
						var swVersion = localStorage.getItem("de-gw-swVersion");
						txt += '<a class="btn" href="edit_group_members.html?group=' + id + '&v=' + swVersion + '">Edit Members</a>';
					} else {
						txt += '<a class="btn" href="edit_group_members.html?group=' + id + '">Edit Members</a>';
					}

					if (deviceType != "ZHASwitch") {
						txt += '<a class="btn btn-danger" href="#" onclick="showDeleteGroupModal(' + id + ');return false;">Delete</a>';
					}

					txt += '</div><br /></div>';

					if ((k % 2) === 0) {
						txtLeft += txt;
					}
					if ((k % 2) === 1) {
						txtRight += txt;
					}
					k++;
				}
			}
		}
	//}
    txtLeft += '</div>';
    txtRight += '</div>';

    $('.groups').html(txtLeft + txtRight);
    app.config = config;
}

function moveUp(id) {
    var thisGroup = $('div#'+id);
	var prevGroup = $('div#'+id).prev();
	alert(prevGroup.parent().html());
	if (prevGroup.html() != undefined && prevGroup.html() != "") {
		prevGroup.before('<div id="'+ id +'">' + thisGroup.html() + '</div>');
		thisGroup.html("");
	}
}

function moveDown(id) {

}

// get full configuration
function getFullConfiguration() {

    $.ajax({
        url: 'api/' + apikey,
        dataType: 'json',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        //processData: false,
        success: function(json, status, xhr) {
            // make available for caching
            sessionStorage.config = xhr.responseText;
            clearAlert();
            displayGroups(json);
			clearUnusedLocalStorageKeys(json);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

            default:
                setTimeout(getFullConfiguration, 1000);
                showAlert('alert-error', '<b>Error!</b> Lost connection, retry in one second ...');
                break;
            }
        },
        timeout: 8000
    });

}

function createGroup(name) {

    var out = { "name": name };

    $.ajax({
        url: 'api/' + apikey + '/groups',
        dataType: 'json',
        type: 'POST',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        //processData: false,
        data: JSON.stringify(out),
        success: function(json) {
            // force reload
            sessionStorage.removeItem("config");
            location.reload(true);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
            //setTimeout(updateLights, 15000);
        }//,
        //timeout: 2000,
    });

}

function saveGroupSequence(sortedLeft, sortedRight) {
	$.ajax({
		url: 'api/' + apikey + '/userparameter/groupssequenceleft',
		dataType: 'json',
		type: 'PUT',
		cache: false,
		contentType: 'application/json; charset=utf-8',
		headers: { 'Accept': apiversion },
		data: JSON.stringify(sortedLeft),
		success: function(json) {
			saveGroupSequenceRight(sortedRight);
		},
		error: function(jqXHR, textStatus, errorThrown) {
			showAlert('alert-error', '<b>Error!</b> Could not save groups position', '#sortGroupsInfo');
			console.log("textStatus:", textStatus + ' ' + errorThrown);
			console.log(jqXHR.responseText);
		}
	});
}

function saveGroupSequenceRight(sortedRight) {
	$.ajax({
		url: 'api/' + apikey + '/userparameter/groupssequenceright',
		dataType: 'json',
		type: 'PUT',
		cache: false,
		contentType: 'application/json; charset=utf-8',
		headers: { 'Accept': apiversion },
		data: JSON.stringify(sortedRight),
		success: function(json) {
			showAlert('alert-success', '<b>Ok!</b> Saving groups position successful', '#sortGroupsInfo');
		},
		error: function(jqXHR, textStatus, errorThrown) {
			showAlert('alert-error', '<b>Error!</b> Could not save groups position', '#sortGroupsInfo');
			console.log("textStatus:", textStatus + ' ' + errorThrown);
			console.log(jqXHR.responseText);
		}
	});
}

function showDeleteGroupModal(id) {
    if (id != undefined) {
		var name = "";

		if (app.config.groups) {
			var g = app.config.groups[id];
			name = g.name
		}

		$('#btnDeleteGroup').data('id', id);
		$('#deleteGroupModalLabel').html('Delete Group ' + name + '?');
		$('#deleteGroupModal').modal('show');
	}
}

function deleteGroup(id) {
    $.ajax({
        url: 'api/' + apikey + '/groups/' + id,
        dataType: 'json',
        type: 'DELETE',
        cache: false,
        headers: { 'Accept': apiversion },
        //contentType: 'application/json; charset=utf-8',
        //processData: false,
        success: function(json) {
            // force reload
            sessionStorage.removeItem("config");
			localStorage.removeItem("whitebarGroup-"+id);
			localStorage.removeItem("lightssequence-"+id);
			localStorage.removeItem("visible-"+id);
            //location.reload(true);
			$('#'+ id).html(""); // faster then reload on rpi and ff (solution for delete kitchen bug)
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
            //setTimeout(updateLights, 15000);
        }//,
        //timeout: 2000,
    });
}

function clearUnusedLocalStorageKeys(config) {
	if (config != undefined) {
		// clear whitebar hidden status of deleted lights
		var lightIds = [];
		for (var lid in config.lights) {
			lightIds[lightIds.length] = lid;
		}
		for (var key in localStorage) {
			if (key.indexOf("whitebar-") != -1) {
				var id = key.substring(9, key.length);
				if (config != undefined && !_.contains(lightIds, id)) {
					localStorage.removeItem(key);
				}
			}
		}
		// clear whitebar hidden status of deleted groups
		var groupIds = [];
		for (var gid in config.groups) {
			groupIds[groupIds.length] = gid;
		}
		for (var key in localStorage) {
			if (key.indexOf("whitebarGroup-") != -1) {
				id = key.substring(14, key.length);
				if (config != undefined && !_.contains(groupIds, id)) {
					localStorage.removeItem(key);
				}
			}
			// clear visible status of deleted groups
			if (key.indexOf("visible-") != -1) {
				id = key.substring(8, key.length);
				if (config != undefined && !_.contains(groupIds, id)) {
					localStorage.removeItem(key);
				}
			}
			// clear lights sequence of deleted groups
			if (key.indexOf("lightssequence-") != -1) {
				id = key.substring(15, key.length);
				if (config != undefined && !_.contains(groupIds, id)) {
					localStorage.removeItem(key);
				}
			}
		}
	}
}
