import { computed, reactive } from 'vue'
import { RECIPROCAL, STAGE_WIDTH, STAGE_HEIGHT } from '../level/def'
import type { Item, ItemQuality } from '../level/items'

export interface InventoryItem extends Item {
  amount: number
  quality: ItemQuality | null
}

export interface Player extends Moveable {
  inventory: InventoryItem[]
}

const player = reactive<Player>({
  x: Math.round((STAGE_WIDTH + 2) / 2),
  y: Math.round((STAGE_HEIGHT + 2) / 2),
  lastDir: 0,
  vx: 0,
  vy: 1, // always falling, because of gravity
  inventory: [], // not yet in use
})

const pocket = (newItem: Item) => {
  const existing = player.inventory.find(item => item.name === newItem.name)

  if (existing) {
    existing.amount += 1
    return existing.amount
  }
  player.inventory.push({
    quality: null,
    amount: 1,
    ...newItem
  })
  return 1
}

const unpocket = (oldItem: Item) => {
  const existingIndex = player.inventory.findIndex(item => item.name === oldItem.name)

  if (existingIndex < 0) return 0

  const existing = player.inventory[existingIndex]

  if (existing.amount > 1) {
    existing.amount -= 1
    return existing.amount
  }
  player.inventory.splice(existingIndex, 1)
  return 0
}

export default function usePlayer() {
  const dx = computed(() => player.vx * RECIPROCAL)
  const dy = computed(() => player.vy * RECIPROCAL)
  const direction = computed(() => (player.lastDir < 0 ? 'left' : 'right'))

  return { player, direction, dx, dy, pocket, unpocket }
}
