from Code.Communication.Direction import Direction
from Code.Config import GeneralConfig, SquareConfig
from Code.UI import Square
from Code.UI.Shape import Shape
from Code.UI.Shapes import Shapes
from Code.UI.Square import Square


class Field:
	def __init__(self):
		self.width = GeneralConfig.fields_amount_x + 2
		self.height = GeneralConfig.fields_amount_y + 2
		self.field_shift = -10
		self.shapes = Shapes()
		self.squares = self._creat_squares()

	def get_square_on_click_pos(self, mousclick_pos):
		index_x = 0
		index_y = 0
		for line in self.squares:
			index_y += 1
			index_x = 0
			for square in line:
				index_x += 1
				if square.rect.collidepoint(mousclick_pos):
					return (index_y, index_x)

	def create_shape(self, shape: Shape, start_square_pos):
		self.squares = self.shapes.create_shape(start_square_pos,self.squares, shape)

	def _creat_squares(self):
		squares = [
			[Square(x_pos=j * SquareConfig.width + self.field_shift, y_pos=i * SquareConfig.height + self.field_shift)
			 for i in range(self.height)] for
			j in range(self.width)]

		return squares

	def update_squares(self, squares):
		self.squares = squares

	def draw_squares(self, window):
		for x in self.squares:
			for y in x:
				y.draw(window)

	def get_edges(self) -> dict:
		return {Direction.LEFT: self.get_left_edge(), Direction.RIGHT: self.get_right_edge(),
		        Direction.TOP: self.get_top(), Direction.BOTTOM: self.get_bottom_edge()}

	def get_edge(self, edg_pos: Direction) -> list:
		return self.get_edges()[edg_pos]

	def get_top(self):
		top_squares = []
		for y in self.squares:
			top_squares.append(y[1].active)

		return top_squares

	def get_bottom_edge(self):
		right_squares = []
		for y in self.squares:
			right_squares.append(y[len(y) - 2].active)
		return right_squares

	def get_left_edge(self):
		left_squares = []
		for x in self.squares[1]:
			left_squares.append(x.active)
		return left_squares

	def get_right_edge(self):
		right_squares = []

		for x in self.squares[len(self.squares[0]) - 2]:
			right_squares.append(x.active)

		return right_squares

	def fill_ghost_edge(self, value: list):

		edge_fn = {Direction.LEFT: self.fill_left_ghost_edge, Direction.RIGHT: self.fill_right_ghost_edge,
		           Direction.TOP: self.fill_top_ghost_edge, Direction.BOTTOM: self.fill_bottom_ghost_edge}

		edge_fn(value)

	def fill_right_ghost_edge(self, value: list):
		# if len(value)== self.square.
		for i in range(len(value)):
			self.squares[len(self.squares[0]) - 1][i].active = value[i]

	def fill_left_ghost_edge(self, value: list):
		for i in range(len(value)):
			self.squares[0][i].active = value[i]

	def fill_top_ghost_edge(self, value):
		pass

	def fill_bottom_ghost_edge(self, value):
		pass
