$ ->
  chartInstance = null

  $('#report-benchmarks').on 'change', (e) ->
    $('#report-tests option').prop('selected', false)

  $('#reports-download').on 'click', (e) ->
    e.preventDefault()
    canvas = $('#benchmark-chart')[0]
    a = document.createElement 'a'
    a.href = canvas.toDataURL 'image/png'
    a.download = 'chart.png'
    a.click()

  $('#reports-button').on 'click', (e) ->
    e.preventDefault()
    $('#reports-download').attr('disabled', true)
    chartInstance.destroy() if chartInstance

    benchmarkId = $('#report-benchmarks').val()
    testIds = $('#report-tests').val()

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

    data =
      labels: []
      datasets: []

    switch benchmarkData.scoring
      when 'pts'
        data.datasets.push({
          label: 'Average Score'
          data: []
        })
      when 'fps'
        data.datasets.push({
          label: 'Average FPS'
          data: []
        })
        data.datasets.push({
          label: 'Minimum FPS'
          data: []
        })
      when 'ms'
        data.datasets.push({
          label: 'Average Frame Time'
          data: []
        })
        data.datasets.push({
          label: 'Minimum Frame Time'
          data: []
        })

    for testId in testIds
      try
        testSearchParams = new URLSearchParams
          test_id: testId
        testRes = await fetch("/api/v1/test/details?#{testSearchParams}")
        testData = await testRes.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)

        data.labels.push(testData.name)
        data.datasets[0].data.push(resultAverage.avgScore)
        console.log(data.datasets[0].data)
        switch benchmarkData.scoring
          when 'fps', 'ms'
            data.datasets[1].data.push(resultAverage.minScore)
      catch error
        console.error 'An error occurred while fetching benchmark results.', error

    ctx = $('#benchmark-chart')[0].getContext('2d')

    options =
      indexAxis: 'y'
      plugins:
        title:
          display: true
          text: benchmarkData.name
          font:
            size: '24'
        datalabels:
          anchor: 'end'
          align: 'left'
          color: 'black'
          font:
            weight: 'bold'
          formatter: (value) -> value
      scales:
        y:
          beginAtZero: true

    chartInstance = new Chart ctx,
      type: 'bar'
      data: data
      options: options
      plugins: [ChartDataLabels]

    $('#reports-download').attr('disabled', false)
    $('#benchmark-chart').removeClass('disabled')
