import store from 'store'

import Game from './logic/game'
import field from './components/field'
import snake from './components/snake'
import shape from './components/shape'
import score from './components/score'
import apple from './components/apple'
import borders from './components/borders'
import gameover from './components/gameover'
import startscreen from './components/startscreen'
import toplist from './components/toplist'
import pause from './components/pause'

import Vector from 'vector'

const dimensions = new Vector(25, 40)
const objects = {
	apple: new Vector(),
	snake: {
		segments: [],
		direction: new Vector(0, 0),
		newDirection: new Vector(0, 0),
	},
	field: [],
	shape: {
		segments: [],
		direction: new Vector(),
	},
}

const current = {
	stage: 0, // 0 - startscreen, 1 - gameplay, 2 - gameover,
}

const menu = [{ text: 'Начать', stage: 1 }, { text: 'Рекорды', stage: 3 }]

store.options = {
	cells: {
		size: 20,
	},
	current,
	dimensions,
	objects,
	menu,
}

// TODO: rewrite
store.keyboard.downActions = {
	up: () => store.keyboard.keys['KeyW'] || store.keyboard.keys['ArrowUp'],
	down: () => store.keyboard.keys['KeyS'] || store.keyboard.keys['ArrowDown'],
	left: () => store.keyboard.keys['KeyA'] || store.keyboard.keys['ArrowLeft'],
	right: () =>
		store.keyboard.keys['KeyD'] || store.keyboard.keys['ArrowRight'],
}

store.keyboard.pressedActions = {
	up: () =>
		store.keyboard.pressed['KeyW'] || store.keyboard.pressed['ArrowUp'],
	down: () =>
		store.keyboard.pressed['KeyS'] || store.keyboard.pressed['ArrowDown'],
	enter: () =>
		store.keyboard.pressed['Space'] || store.keyboard.pressed['Enter'],
	exit: () =>
		store.keyboard.pressed['Escape'] || store.keyboard.pressed['Backspace'],
}

const game = new Game()
game.restart()

const drawBoard = () => {
	field(objects.field)
	if (current.mode === 0) {
		snake(objects.snake)
		apple(objects.apple)
	} else {
		shape(objects.shape)
	}

	score()
}

export default () => {
	store.ctx.save()
	store.ctx.translate(30, 30)

	borders(dimensions.x, dimensions.y)

	if (current.stage === 1) {
		game.update()
		drawBoard()
	} else if (current.stage === 0) {
		const result = startscreen()
		if (result === 1) {
			game.restart()
		}
	} else if (current.stage === 2) {
		gameover()
		drawBoard()
	} else if (current.stage === 3) {
		toplist()
	} else if (current.stage === 4) {
		pause()
		drawBoard()
	}

	store.ctx.restore()

	store.keyboard.process()
}
