var applyLightSort = false;
var lightsChecked = 0;
var count = 0;
var resetLightId = "0";
var resetLIghtName = "";
var resetMultipleEndpoints = [];
var th; // setTimeoutHandle

function connectGateway(id) {

	var d = { "pairing": true };
	$.ajax({
        url: 'api/' + apikey + '/gateways/' + id + '/state',
        dataType: 'json',
		data: JSON.stringify(d),
        type: 'PUT',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        success: function(json) {
			clearTimeout(th);
			th = setTimeout(getGateways, 500);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

            default:
                showAlert('alert-error', '<b>Error!</b> Failed to update configuration');
                break;
            }
        },
        timeout: 8000
    });
}

function updateUi(json) {
		for (var id in json) {

			var gw = json[id];

			if (gw.name === undefined) {
				gw.name = 'Gateway ' + id;
			}

			var $row = $('#tbl-gw tr[data-gwid="' +  id + '"]');

			if ($row.length === 0) {
				$('#tbl-gw tbody').append('<tr data-gwid="' +  id + '"><td ></td><td ></td><td ></td><td ></td><td ></td></tr>');
				$row = $('#tbl-gw tr[data-gwid="' +  id + '"]');
			}

			var $td = $row.find('td');

			if ($td.length === 5) {
				$($td[0]).html('<a href="http://' + gw.ip + ':' + gw.port + '" target="_blank">' + gw.name + '</a>');
				$($td[1]).html(gw.ip);
				$($td[2]).html(gw.port);
				$($td[3]).html(gw.state);

				if (gw.state === "connected") {
					$($td[4]).html('<a class="btn" href="edit_gateway_config.html?id=' + id + '">Edit</a>')
				} else if (gw.state === "not authorized"){
					if (!gw.pairing) {
						$($td[4]).html('<a class="btn" href="#" onclick="connectGateway('  + id + '); return false;">Connect</a>')
					} else {
						$($td[3]).html("connecting")
						$($td[4]).html('')
					}
				} else {
					$($td[4]).html('');
				}
			}

		}
}

function getGateways() {

    $.ajax({
        url: 'api/' + apikey + '/gateways',
        dataType: 'json',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        success: function(json) {
            clearAlert();
			clearTimeout(th);
			th = setTimeout(getGateways, 10000);
            updateUi(json);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

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

// init
$(document).ready(function() {
	getGateways();
	initBranding();
});

