import text from 'snake-tetris/components/text'
import rect from 'snake-tetris/components/rect'

import store from 'store'

const offset = [100, 200]

class Menu {
	constructor() {
		this.selected = 0
		this.rectPos = offset[1] - 12
	}

	checkKeyb(items) {
		const keys = store.keyboard.pressedActions

		if (keys.up()) {
			if (this.selected - 1 >= 0) this.selected--
		} else if (keys.down()) {
			if (this.selected + 1 < items.length) this.selected++
		}
	}

	render(items) {
		this.checkKeyb(items)

		const targetPos = 50 * this.selected + offset[1] - 13
		if (this.rectPos !== targetPos) {
			const sign = Math.sign(targetPos - this.rectPos)
			let newPos = this.rectPos + (sign * store.dt) / 2
			newPos =
				sign > 0
					? Math.min(newPos, targetPos)
					: Math.max(newPos, targetPos)
			this.rectPos = newPos
		}

		items.forEach((item, i) => {
			const isSelected = i === this.selected

			if (isSelected) {
				rect({
					x: offset[0],
					y: this.rectPos,
					width: 200,
					height: 50,
					color: '#000',
				})
			}

			text({
				x: 100 + offset[0],
				y: 50 * i + offset[1],
				text: item.text,
				color: '#000',
				align: 'center',
			})
		})
	}
}

export default Menu
