import store from 'store'

import SnakeController from './snake-controller'
import ShapeController from './shape-controller'
import FieldController from './field-controller'
import ScoreController from './score-controller'

import toplist from './toplist'

export default class Game {
	constructor() {
		this.snakeController = new SnakeController()
		this.shapeController = new ShapeController()
		this.fieldController = new FieldController()
		this.scoreController = new ScoreController()
	}

	update() {

		if (store.keyboard.pressedActions.exit()) {
			store.options.current.stage = 4
			return
		}

		if (store.options.current.mode === 0) {
			this.snakeUpdate()
		} else {
			this.shapeUpdate()
		}
	}

	snakeUpdate() {
		const result = this.snakeController.update()
		if (result === 1) {
			store.options.current.mode = 1
			this.scoreController.snake()
			this.shapeController.makeShape()
		} else if (result === 2) {
			this.setGameOver()
		}
	}

	shapeUpdate() {
		const result = this.shapeController.update()
		if (result === 1) {
			const lines = this.fieldController.update()
			this.scoreController.lines(lines)

			this.restartApple()
			this.snakeController.restart()

			store.options.current.mode = 0
		}
	}

	restart() {
		const current = store.options.current
		current.mode = 0
		current.score = {
			total: 0,
			lines: 0,
		}
		current.snakeLength = 3
		current.speed = 1,

		this.snakeController.restart()
		this.fieldController.restart()
		this.restartApple()
	}

	restartApple() {
		const width = store.options.dimensions.x

		const x = (Math.random() * width) | 0

		const max = store.options.objects.field.findIndex(row => {
			return row.some(cell => cell > 0)
		})

		if (max < 3) {
			this.setGameOver()
			return
		}
		const y = ((Math.random() * (max - 1) ) | 0) + 1

		store.options.objects.apple.xy(x, y)
	}

	setGameOver() {
		store.options.current.stage = 2
		const { score, snakeLength, speed } = store.options.current
		toplist.add({
			total: score.total,
			lines: score.lines,
			snakeLength,
			speed,
		})
	}
}
