const { postTemp, getCurrentTemp } = require('./honeywell')
const { onTempChangeRequested } = require('./slack')
require('./games')

const coolMode = 'Cool'
const heatMode = 'Heat'

const minTemp = 68
const maxTemp = 80

let lowTemp = 72
let highTemp = 74

const cleanTemp = temp => {
  if (temp > maxTemp) {
    temp = maxTemp
  } else if (temp < minTemp) {
    temp = minTemp
  }
  return temp
}

onTempChangeRequested(change => {
  const { indoorTemperature } = getCurrentTemp()
  switch (change) {
    case 'Hotter': {
      lowTemp += 2
      highTemp += 2
      break
    }
    case 'Colder': {
      lowTemp -= 2
      highTemp -= 2
      break
    }
    case 'Good': {
      return
    }
  }

  highTemp = cleanTemp(highTemp)
  lowTemp = cleanTemp(lowTemp)

  const mode =
      indoorTemperature < lowTemp ? heatMode // Heat if lower than low
        : indoorTemperature > highTemp ? coolMode // Cool if hotter than high
          : change === 'Hotter' ? heatMode : coolMode // Otherwise (lower priority) follow the requested change

  if (!mode) {
    return
  }

  postTemp({
    coolSetpoint: lowTemp,
    heatSetpoint: highTemp,
    mode
  })
})
