function get_human_readable_time(time){
    minutes = (time > 60) ? Math.floor(time/60) : 0;
    seconds = (time%60).toFixed(0);
    return `${minutes}:${seconds}`;
}

// liefert einen Result-Text entweder für eine Zahl oder einen Text zurück
function result_text(result) {
	const result_enum = {1: 'Negativ', 2: 'Positiv', 3: 'Ungültig'};
	if (Number.isInteger(result))
		return result_enum[Number(result)];
	else {
		switch (result.toLowerCase()) {
			case "negative":
				return result_enum[1];
				break;
			case "positive":
				return result_enum[2];
				break;
			default:
				return result_enum[3];
				break;
		}
	}
}

// liefert die Bootstrap-Farbcodes für ein Ergebnis
function result_color(result) {
	const result_color = {1: 'success', 2: 'danger', 3: 'dark'};

	if (Number.isInteger(result)) return result_color[Number(result)];
	else {
		switch (result.toLowerCase()) {
			case "negativ":
				return result_color[1];
				break;
			case "positiv":
				return result_color[2];
				break;
			default:  // includes invalid
				return result_color[3];
				break;
		}
	}
}
 
function parse_and_show_pluslife_result(overall_result, channel_results){
	$("#testresult").append(result_text(overall_result));
	if (result_text(overall_result) == "Ungültig")
		$("#testresult").addClass("ungueltig");
	else
		$("#testresult").addClass(result_text(overall_result).toLowerCase());

    channel_results_html = '';
    for (const [channel, data] of Object.entries(channel_colors)) {
        var result = result_text(channel_results[Number(channel)]);
        var color = result_color(result);
        if (channel == "3"){
            result = (result == "Positiv") ? "OK" : "NOK";
            color = (result == "OK") ? "primary" : color;
        }

        channel_results_html += `<span class="badge rounded-pill text-bg-${color} me-1">${channel}: ${result.slice(0,3)}</span>`;
    }
    $("#testresult_channels").append(channel_results_html);
}

function update_chart(timestamp, overall_result, result_channels, sampledata){
	var dateoptions = {
		weekday: "short",
		year: "numeric",
		month: "long",
		day: "numeric",
		hour: "numeric",
		minute: "2-digit",
		timeZoneName: "short",
	};
	var datum = new Date(timestamp).toLocaleString("de-DE", dateoptions);
    $("#testdate").append(datum);

    if (overall_result || result_channels)
        parse_and_show_pluslife_result(overall_result, result_channels);

    document.getElementById('datacontainer').hidden = false;

    chart.data.labels.length = 0;
    chart.data.datasets.forEach((dataset) => {
        dataset.data.length = 0;
    });
    var offset = -1;
    var data_index = 0;
    var filled_array = Array(1000).fill(-1);
    sampledata.forEach((sample) => {
        var human_readable_time = get_human_readable_time(Math.floor(sample.samplingTime/10));
        if (! chart.data.labels.includes(human_readable_time)){
            chart.data.labels.push(human_readable_time);
            offset += 1;
        }
        data_index = offset*7 + sample.startingChannel;
        filled_array[data_index] = sample.firstChannelResult/64;

        chart.data.datasets.forEach((dataset) => {
            if (dataset.channel == sample.startingChannel)
                dataset.data.push(sample.firstChannelResult);
        });
    });
    chart.update();
}

function delete_test() {
	var id = new URLSearchParams(window.location.search).get('id');

	$.ajax({
		url: "delete.php?id=" + id,
		async: false,
		dataType: "json",
		success: function (data) {
			window.location.href="index.php";
		},
		error: function (request, status, error) {
			show_error("Fehler: " + error);
		}
	});
}

function show_error(text) {
	console.log(text);
	$("#error").append(text);
	$("#error").show();
}

(function() {
	if (data != null && typeof data == 'object') {
	    update_chart(Date.parse(json.test.data.temperatureSamples[0].time),
			json.test.result.detectionResult,
			json.test.result.channelResults,
			json.test.data.samples);
	} else {
		show_error("Konnte Testdaten nicht laden");
	}

	const deleteModal = new bootstrap.Modal('#deleteModal', { keyboard: false, backdrop: 'static' });
	$("#btn-delete-yes").click(function () {
		delete_test();
		deleteModal.hide();
	});
	$("#btn-delete").click(function () {
		deleteModal.show();
	});
	// ARIA Warnung wg. aria-hidden umgehen:
	$('#deleteModal').on('hide.bs.modal', () => { document.activeElement.blur(); });
})();

