import { ref } from 'vue'

export default function useInput() {
  let inputX = ref(0)
  let inputY = ref(1)
  let running = ref(false)
  let digging = ref(false)
  let paused = ref(false)
  let help = ref(false)
  let inventory = ref(false)

  let wasPaused = false

  function handleKeyDown(event: KeyboardEvent) {
    switch (event.key) {
      case 'Shift':
        running.value = true
        break
      case 'ArrowUp':
        inputY.value = -1
        break
      case 'ArrowDown':
        inputY.value = 1
        break
      case 'ArrowRight':
        inputX.value = 1
        break
      case 'ArrowLeft':
        inputX.value = -1
        break
      case 'p':
        if (!help.value) paused.value = !paused.value
        if (wasPaused && !paused.value) wasPaused = false
        break
      case ' ':
        digging.value = true
        break
      case '?':
        if (paused.value && !help.value) wasPaused = true
        help.value = !help.value
        paused.value = help.value || wasPaused
        break
      case 'i':
        if (paused.value && !inventory.value) wasPaused = true
        inventory.value = !inventory.value
        paused.value = inventory.value || wasPaused
        break
    }
  }

  function handleKeyUp(event: KeyboardEvent) {
    switch (event.key) {
      case 'Shift':
        running.value = false
        break
      // Arrow Keys
      case 'ArrowUp':
      case 'ArrowDown':
        inputY.value = 1
        break
      case 'ArrowRight':
        inputX.value = inputX.value === 1 ? 0 : -1
        break
      case 'ArrowLeft':
        inputX.value = inputX.value === -1 ? 0 : 1
        break
      case ' ':
        digging.value = false
        break
    }
  }

  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('keyup', handleKeyUp)

  document.addEventListener('keydown', handleKeyDown)
  document.addEventListener('keyup', handleKeyUp)

  return {
    inputX,
    inputY,
    running,
    digging,
    paused,
    help,
    inventory,
  }
}
