import text from '../drawers/text'
import rect from '../drawers/rect'
import transform from '../drawers/transform'

import store from '../store'

class Menu {
	constructor(items, offset = { x: 0, y: 0 }) {
		this.selected = 0
		this.items = items
		this.offset = offset
	}

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

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

	render() {
		this.checkKeyb()

		this.items.forEach((item, i) => {
			transform({
				position: { x: this.offset.x, y: 40 * i + this.offset.y },
				children: () => {
					const isSelected = i === this.selected
					isSelected &&
						rect({ width: 100, height: 40, color: 'black' })
					text({
						text: item.text,
						color: isSelected ? 'white' : 'black',
					})
				},
			})
		})
	}
}

export default Menu
