var gid = null;
var config;
var ERR_DEVICE_GROUP_TABLE_FULL = 302;
var applyPressed = 0;
var lightsAlreadyInGroup = [];
var resetWhitelist = [{"modelid":"FLS-A2","swversion":"201000C6"}];

function displayGroups(config) {

    gid = getURLParameter('group');

    if (gid === null) {
        // go back if no id was specified
        window.location.assign('edit_groups.html');
    }

    var txt = '<div class="span12">';
    var group = undefined;

    for (var id in config.groups) {
        if (id === gid) {
            // found
            group = config.groups[id];
            break;
        }
    }

    if (group === undefined) {
        // go back if no id was specified
        window.location.assign('edit_groups.html');
    }

	var sortArr = [];

	//if (localStorage.getItem("lightssequence-"+gid) != undefined) {
	//	sortArr = localStorage.getItem("lightssequence-"+gid).split(",");
	//}
	if (group.lightsequence != undefined && group.lightsequence.length > 0) {
		sortArr = group.lightsequence;
	}

    txt += '<form>';
    txt += '<table class="table noborder">';
    txt += '<thead>';
    txt += '<th>Name</th><th>Model</th><th>Vendor</th><th>Version</th>';//<th>Remove from App</th>';
    txt += '</thead>';
    txt += '<tbody>';

	for (var s = 0; s < sortArr.length; s++) {
		for (var id in config.lights) {
			if (id === sortArr[s]) {
				var l = config.lights[id];
				var checked = false;
				var disabled = "";
				var muted = "";
				var color = "#fff;";
				var hascolor = (l.state.colormode === undefined) ? false : true;

				l.manufacturername = l.manufacturer || l.manufacturername;

				//dont display white channel of multi-devices
				var mac = l.uniqueid.substring(0,l.uniqueid.indexOf("-"));
				var multideviceWhiteChannel = false;
				//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 && id != i && hascolor == false && masterHasColor == true) {
							multideviceWhiteChannel = true;

							// mark the other light as multidevice master
							config.lights[i].multideviceID = id;
							config.lights[i].multideviceUID = l.uniqueid;
							break;
						}
					}
				//}
				if (!multideviceWhiteChannel) {
					// if already in the group mark checked
					for (var i = 0; i < group.lights.length; i++) {
						if (group.lights[i] == id) {
							checked = true;
							lightsAlreadyInGroup[lightsAlreadyInGroup.length] = id;
							break;
						}
					}

					if (l.state.reachable == false) {
						disabled = " disabled ";
						muted = "muted";
						color = "#999;";
					}

					txt += '<tr class="light" id="' + id + '" data-uid="' + l.uniqueid + '">';
					txt += '<td class="' + muted + '">';
					txt += '<label class="checkbox" style="padding-left:0px;">';
					txt += '<span class="btn"' + disabled + 'style="padding-left:30px; color:' + color + '">';
					txt += '<input type="checkbox"' + disabled + ' data-lid="' + id + '"' + (checked ? ' checked="checked"' : '') + '> ' + l.name
					txt += '</span>';
					txt += '</label>';
					txt += '</td>';
					txt += '<td class="' + muted + '">' + l.modelid + '</td>';
					txt += '<td class="' + muted + '">' + l.manufacturername + '</td>';
					txt += '<td class="' + muted + '">' + l.swversion + '</td>';

					for (var r in resetWhitelist) {
						if (l.modelid.indexOf(resetWhitelist[r].modelid) != -1) {
							txt += '<td><span class="btn btn-danger resetLightBtn" data-lid="'+ id +'">Reset</span></td>';
							break;
						}
					}

					txt += '</tr>';
				}
				break;
			}
		}
	}

	// append lights that where not sorted yet
	//if (sortArr.length < Object.keys(config.lights).length) {
		for (var id in config.lights) {
			if (!_.contains(sortArr, id)) {
				var l = config.lights[id];
				var checked = false;
				var disabled = "";
				var muted = "";
				var color = "#fff;";
				var hascolor = (l.state.colormode === undefined) ? false : true;
				l.manufacturername = l.manufacturer || l.manufacturername;

				//dont display white channel of multi-devices
				var mac = l.uniqueid.substring(0,l.uniqueid.indexOf("-"));
				var multideviceWhiteChannel = false;
				//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 && id != i && hascolor == false && masterHasColor == true) {
							multideviceWhiteChannel = true;

							// mark the other light as multidevice master
							config.lights[i].multideviceID = id;
							config.lights[i].multideviceUID = l.uniqueid;
							break;
						}
					}
				//}
				if (!multideviceWhiteChannel) {
					// if already in the group mark checked
					for (var i = 0; i < group.lights.length; i++) {
						if (group.lights[i] == id) {
							checked = true;
							lightsAlreadyInGroup[lightsAlreadyInGroup.length] = id;
							break;
						}
					}

					if (l.state.reachable == false) {
						disabled = " disabled ";
						muted = "muted";
						color = "#999;";
					}

					txt += '<tr class="light" id="' + id + '" data-uid="' + l.uniqueid + '">';
					txt += '<td class="' + muted + '">';
					txt += '<label class="checkbox" style="padding-left:0px;">';
					txt += '<span class="btn"' + disabled + 'style="padding-left:30px; color:' + color + '">';
					txt += '<input type="checkbox"' + disabled + ' data-lid="' + id + '"' + (checked ? ' checked="checked"' : '') + '> ' + l.name
					txt += '</span>';
					txt += '</label>';
					txt += '</td>';
					txt += '<td class="' + muted + '">' + l.modelid + '</td>';
					txt += '<td class="' + muted + '">' + l.manufacturername + '</td>';
					txt += '<td class="' + muted + '">' + l.swversion + '</td>';

					for (var i in resetWhitelist) {
						if (l.modelid && l.modelid.indexOf(resetWhitelist[i].modelid) != -1) {
							txt += '<td><span class="btn btn-danger resetLightBtn" data-lid="'+ id +'">Reset</span></td>';
							break;
						}
					}

					txt += '</tr>';
				}
			}
		}
	//}
    txt += '</tbody>';
    txt += '</table>';
    txt += '</form>';
    txt += '</div>';

    $('.headerGroupName').html(group.name);
    $('.groups').html(txt);
}

function getFullConfiguration() {

    $.ajax({
        url: 'api/' + apikey,
        dataType: 'json',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        success: function(json) {
            clearAlert();
            displayGroups(json);
			config = json;
			checkAllChecked();

			// show/hide features based on update channel
			$('[data-channel]').each(function(){
				if ($(this).attr('data-channel').indexOf(config.config.updatechannel) != -1 &&
				    (!$(this).hasClass("advanced-sys") && !$(this).hasClass("advanced-nw"))) {
					$(this).removeClass('hidden');
				}
			});
        },
        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 onSubmit() {
	applyPressed += 1;

    // only if we have a valid group id
    if (gid === null) {
        return;
    }

    var lights = [];
	var multiDeviceIds = [];

    $("input[data-lid]").each(function( index ) {
        if (this.checked) {
            lights.push($(this).attr('data-lid'));

			// if light has a little multidevice brother
			//if (config.config.rgbwdisplay === "1") {
				for (i in config.lights) {
					if (i == $(this).attr('data-lid')) {
						var multiDeviceId = config.lights[i].multideviceID;
						if (multiDeviceId != undefined) {
							//double check if it is realy the correct light
							if (config.lights[i].multideviceUID == config.lights[multiDeviceId].uniqueid) {
								lights.push(multiDeviceId);
								multiDeviceIds.push(multiDeviceId);
								break;
							}
						}
					}
				}
			//}
		}
    });

    $.ajax({
        url: 'api/' + apikey + '/groups/' + gid,
        dataType: 'json',
        type: 'PUT',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        data: "{ \"lights\": " + JSON.stringify(lights) + ", \"multideviceids\": " + JSON.stringify(multiDeviceIds) + " }",
        success: function(json) {
			var error = false;
			for (i in json) {
				if (json[i].error && json[i].error.type == ERR_DEVICE_GROUP_TABLE_FULL) {
					var addr = json[i].error.address;
					var lid = addr.substring(addr.indexOf("lights/")+7, addr.length);
					if (!_.contains(multiDeviceIds,lid) && !_.contains(lightsAlreadyInGroup,lid)) {
						appendWarning('alert-warning', "<b>Warning! </b>" + json[i].error.description);
						error = true;
					}
				}
			}
			if ((!error) || (error && applyPressed > 1)){
				applyPressed = 0;
				window.location.assign('edit_groups.html');
			}
        },
        error: function(jqXHR, textStatus, errorThrown) {
            showAlert('alert-error', '<b>Error!</b> Failed to set group members.');
        }//,
        //timeout: 2000,
    });
}

function saveLightSequence(sortedLights) {
	gid = getURLParameter("group");
    // save in localStorage
	//localStorage.setItem("lightssequence-"+gid, sortedLights);
	//save at gateway
    $.ajax({
        url: '/api/' + apikey + '/groups/' + gid,
        type: 'PUT',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        data: '{"lightsequence":' + JSON.stringify(sortedLights) + '}',
        dataType: 'json',
        success: function(data) {
			console.log("save lightseqeunce successful");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
        },
        timeout: 10000
    });
}

/**
 * Helper Function to append Warnings
 */
function appendWarning(alert, text, container) {
    if (typeof(container) === 'undefined') {
        container = '#warnings';
    }

    var d = new Date();
    var timestr = d.toUTCString();
    var txt = "";

    txt += '<div style="" class="alert ' + alert + '">';
    txt += text;
    txt += ' <span class="pull-right hidden-phone">';
    txt += '</span></div>';

	setTimeout(function() {
		$(container).append(txt).scrollintoview();
	}, 250);
}

function filter(filterString) {
	var rows = $("tbody tr").size();
	var hiddenrows = 0;
	$("tbody tr").each(function() {
		var html = "";
		html += $(this).attr('data-uid') + "/";
		$(this).children().each(function(){
			html += $(this).text() + "/";
		});
		html = html.toLowerCase();
		if (filterString == "") {
			$(this).removeClass('hidden');
		} else if (html.indexOf(filterString.toLowerCase()) == -1) {
			$(this).addClass('hidden');
			hiddenrows++;
		} else {
			$(this).removeClass('hidden');
		}
		if (hiddenrows === rows) {
			$('#filterInput').css('background-color','#ffcccc');
			$('#filterInput').css('box-shadow','0px 0px 10px 0px rgba(255,50,50,1)');
		} else {
			$('#filterInput').css('background-color','#fff');
			$('#filterInput').css('box-shadow','none');
		}
	});
}

function deleteLight(id,reset) {
	$.ajax({
        url: '/api/' + apikey + '/lights/' + id,
        type: 'DELETE',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        data: '{"reset":'+ reset +'}',
        dataType: 'json',
        success: function(data) {
			console.log("light " + id + " reset success");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
        },
        timeout: 10000
    });
}