const pingCanvas = document.getElementById('ping-graph-canvas')
const profitCanvas = document.getElementById('profit-graph-canvas')

const ctxPing = pingCanvas.getContext('2d')
const ctxProfit = profitCanvas.getContext('2d')
const pingChart = new Chart(ctxPing, {
  type: 'line',
  data: {
    labels: [],
    datasets: [
      {
        label: 'BinMaster Server Ping',
        data: [],
        fill: false,
        pointBorderColor: 'white',
        borderColor: 'blue'
      },
      {
        label: 'Hypixel Ping',
        data: [],
        fill: false,
        pointBorderColor: 'white',
        borderColor: 'red'
      }
    ]
  }
})

const profitChart = new Chart(ctxProfit, {
  type: 'line',
  data: {
    labels: [],
    datasets: [
      {
        label: 'Estimated profit',
        data: [],
        fill: false,
        pointBorderColor: 'white',
        borderColor: 'blue'
      }
    ]
  }
})

function updatePing (date, { ping, actualPing }) {
  for (const dataset of pingChart.data.datasets) {
    if (dataset.label.includes('BinMaster')) {
      dataset.data.push(ping)
    } else {
      dataset.data.push(actualPing)
    }

    if (dataset.data.length >= 30) {
      dataset.data.shift()
    }
  }

  if (pingChart.data.labels.length >= 30) {
    pingChart.data.labels.shift()
  }

  pingChart.data.labels.push(`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`)
  pingChart.update()
}

function updateProfit (date, { estProfit }) {
  for (const dataset of profitChart.data.datasets) {
    dataset.data.push(estProfit)

    if (dataset.data.length >= 30) {
      dataset.data.shift()
    }
  }

  if (profitChart.data.labels.length >= 30) {
    profitChart.data.labels.shift()
  }

  profitChart.data.labels.push(`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`)
  profitChart.update()
}

socket.on('ping', (ping, actualPing) => {
  console.log(`Received ping to BinMaster Server: ${ping.toFixed(2)}, and to Hypixel: ${actualPing.toFixed(2)}`)
  updatePing(new Date(), { ping: ping.toFixed(2), actualPing: actualPing.toFixed(2) })
})

socket.on('profitData', (estProfit) => {
  console.log(`Received estimate profit: ${estProfit}`)
  updateProfit(new Date(), { estProfit })
})
