testId = $('#results-table').data('test-id')

fetchTestBenchmarkResults = (testId, benchmarkId) ->
	try
		benchmarkSearchParams = new URLSearchParams
			benchmark_id: benchmarkId
		benchmarkRes = await fetch("/api/v1/benchmark/details?#{benchmarkSearchParams}")
		benchmarkData = await benchmarkRes.json()

		resultSearchParams = new URLSearchParams
			test_id: testId
			benchmark_id: benchmarkId
		resultRes = await fetch("/api/v1/result/list?#{resultSearchParams}")
		resultData = await resultRes.json()

		resultAverage = averageResults(resultData)

		tableRow = $("#results-table tr[data-benchmark-id=#{benchmarkId}]")

		tableRow.append('<td><a href="/benchmark/' + benchmarkData.id + '">' + benchmarkData.name + '</a></td>')
		tableRow.append('<td>' + benchmarkData.scoring + '</td>')
		tableRow.append('<td>' + resultData.length + '</td>')

		if resultData.length != 0
			tableRow.append('<td>' + resultAverage.avgScore + '</td>')

			if benchmarkData.scoring == 'fps'
				tableRow.append('<td>' + resultAverage.minScore + '</td>')
				tableRow.append('<td>' + resultAverage.maxScore + '</td>')
			else
				tableRow.append('<td>N/a</td>')
				tableRow.append('<td>N/a</td>')
		else
			tableRow.append('<td>N/a</td>')
			tableRow.append('<td>N/a</td>')
			tableRow.append('<td>N/a</td>')
	catch error
		console.error 'An error occurred while fetching benchmark results.', error

$('#results-table tbody tr').each((index, tr) ->
	benchmarkId = $(tr).data('benchmark-id')
	console.log("Fetching results for benchmark id: " + benchmarkId)
	fetchTestBenchmarkResults(testId, benchmarkId)
)
