import throttle from './throttle'
import Vector from 'vector'
import store from 'store'
import cellType from './cell-type'

const directions = [
	new Vector(0, -1),
	new Vector(1, 0),
	new Vector(0, 1),
	new Vector(-1, 0),
]

export default class {
	constructor() {
		this.moveThrottled = throttle(() => this.move())
	}

	update() {
		const force = this.checkKey('up', 0, 2)
			|| this.checkKey('right', 1, 3)
			|| this.checkKey('down', 2, 0)
			|| this.checkKey('left', 3, 1)

		if (force) {
			return this.moveThrottled(100)
		}

		return this.moveThrottled(500 / store.options.current.speed)
	}

	move() {
		const snake = store.options.objects.snake
		const segments = snake.segments

		snake.direction = snake.newDirection

		const newCoords = Vector.add(segments[0], snake.direction)

		const _cellType = cellType(newCoords)
		if (_cellType === 0) {
			for (let i = segments.length - 1; i > 0; i--) {
				segments[i].copy(segments[i - 1])
			}
			segments[0].add(snake.direction)

			return 0
		} else if (_cellType === 4) {
			return 1
		} else {
			return 2
		}
	}

	checkKey(key, newDirectionIndex, wrongDirectionIndex) {
		const snake = store.options.objects.snake

		const keyPressed = store.keyboard.downActions[key]()
		if (keyPressed && !snake.direction.equalTo(directions[wrongDirectionIndex])) {
			snake.newDirection = directions[newDirectionIndex]
			if (snake.direction.equalTo(snake.newDirection)) {
				return true
			}
		}

		return false
	}

	restart() {
		const snake = store.options.objects.snake
		const center = (store.options.dimensions.x / 2) | 0

		const snakeLength = store.options.current.snakeLength

		snake.segments = new Array(snakeLength).fill(true)
			.map((_, i) => new Vector(center, -i))

		snake.direction = directions[2]
		snake.newDirection = directions[2]
	}
}
