var gwid = null;
var gw = {}
var ownGroups = {}

function updateUi(json) {
		gw = json;

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

		$('.gw-name').each(function() {
			$(this).text(gw.name);
		});

		var $rows = $('#tbl-casc tbody tr');


		if (gw.cascadegroups) {
			var r = 0;
			for (var i = 0; i < gw.cascadegroups.length; i++) {
				var cg = gw.cascadegroups[i];
				var lg = ""
				var rg = ""

				if (cg.local in ownGroups) {
					lg = ownGroups[cg.local].name;
				}

				if (cg.remote in gw.groups) {
					rg = gw.groups[cg.remote];
				}

				if (r < $rows.length ) {
					var $td = $($rows[r]).find('td');

					$($td[0]).html(lg)
					$($td[1]).html(rg)

					r++;
				} else {
					$('#tbl-casc tbody').append('<tr><td>' + lg + '</td><td>' + rg + '</td><td><a href="#" class="btn btn-danger" onclick="removeCascadeGroup(' + cg.local + ',' + cg.remote + '); return false;">Delete</a></td></tr>');
				}
			}
		}
}

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

				case 404:
					window.location.assign("/edit_gateways.html");
					break;

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

function getGateway() {

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

			case 404:
                window.location.assign("/edit_gateways.html");
                break;

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

function removeCascadeGroup(lg, rg) {
		var casc = { "local": lg, "remote": rg };

		$.ajax({
        url: 'api/' + apikey + '/gateways/' + gwid + '/cascadegroup' ,
        dataType: 'json',
		data: JSON.stringify(casc),
        type: 'DELETE',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        success: function(json) {
			location.reload();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

			//case 404:
            //   window.location.assign("/edit_gateways.html");
            //    break;

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

function addCascadeGroupSubmit() {

		$local = $('#selLocalGroup option:selected');
		$remote = $('#selRemoteGroup option:selected');

		if ($local.length !== 1 && $remote.length !== 1) {
			return;
		}

		var lg = $local[0].value;
		var rg = $remote[0].value;
		var casc = { "local": lg, "remote": rg };

		$.ajax({
        url: 'api/' + apikey + '/gateways/' + gwid + '/cascadegroup' ,
        dataType: 'json',
		data: JSON.stringify(casc),
        type: 'POST',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        success: function(json) {
			location.reload();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

			//case 404:
            //   window.location.assign("/edit_gateways.html");
            //    break;

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



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

		gwid = getURLParameter('id');

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

		$('#addCascadeGroupModal').on('show', function (e) {

			if (gw.groups === undefined)
				return e.preventDefault() // stops modal from being shown

			$('#selLocalGroup').html("")

			for (var id in ownGroups) {
				$('#selLocalGroup').append('<option value="' + id + '">' +  ownGroups[id].name +'</option>')
			}

			$('#selRemoteGroup').html("")
			for (var id in gw.groups) {
				$('#selRemoteGroup').append('<option value="' + id + '">' +  gw.groups[id] +'</option>')
			}
		})

        getOwnGroups();
	});



