import pygame as pygame

from Code.Communication.Direction import Direction
from Code.Communication.EdgeSync import EdgeSync
from Code.Communication.Neighbours import Neighbours
from Code.Config import Fonts
from Code.Config import GeneralConfig, Colors
from Code.GameLogic.Rules import Rules
from Code.UI.Field import Field
from Code.UI.Shape import Shape


class GameState:
	def __init__(self, neighbours: Neighbours,counter):

		self.neighbours = neighbours
		self.counter = counter
		self.run = True
		self.is_evolving = False
		self.field = Field()
		self.edge_sync = EdgeSync(self.field.get_edges(), self.counter)
		self.update_field_events = []

	def event_handler(self):
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				self.run = False
			if event.type == pygame.MOUSEBUTTONUP:
				self.update_field_events.append(event)
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE:
					print(f"Gamestate: set evolving to {not self.is_evolving}")
					self.is_evolving = not self.is_evolving
					self.neighbours.toggle_pause(self.is_evolving)
				if event.key == pygame.K_v:
					self.field.create_shape(Shape.VERTICAL_GLIDER_LEFT,
					                        self.field.get_square_on_click_pos(pygame.mouse.get_pos()))
				if event.key == pygame.K_b:
					self.field.create_shape(Shape.VERTICAL_GLIDER_RIGHT,
					                        self.field.get_square_on_click_pos(pygame.mouse.get_pos()))
				if event.key == pygame.K_n:
					self.field.create_shape(Shape.GLIDER_LEFT_DOWN,
					                        self.field.get_square_on_click_pos(pygame.mouse.get_pos()))
				if event.key == pygame.K_m:
					self.field.create_shape(Shape.GLIDER_RIGHT,
					                        self.field.get_square_on_click_pos(pygame.mouse.get_pos()))
				if event.key == pygame.K_y:
					self.field.create_shape(Shape.VERTICAL_GLIDER_RIGHT,
					                        self.field.get_square_on_click_pos(pygame.mouse.get_pos()))
				if event.key == pygame.K_x:
					self.field.create_shape(Shape.VERTICAL_GLIDER_LEFT,
					                        self.field.get_square_on_click_pos(pygame.mouse.get_pos()))

	def update_field_with_input(self, event):
		for line in self.field.squares:
			for square in line:
				if square.rect.collidepoint(event.pos):
					square.update(not square.active)

	def evolve(self):
		rules = Rules()
		self.field.update_squares(rules.evolve_field(self.field))

	def redraw_field(self, window):
		window.fill(Colors.BLACK)
		self.field.draw_squares(window)
		if not self.is_evolving:
			label_font = Fonts.monospace_80
			label = label_font.render("Pause", 1, Colors.ORANGE)
			window.blit(label, (100, 100))

	def update_borders(self):
		self.field.fill_right_ghost_edge(self.neighbours.get_edge(Direction.RIGHT, self.counter))
		self.field.fill_left_ghost_edge(self.neighbours.get_edge(Direction.LEFT, self.counter))
		self.counter_old = self.counter


def run_game(game_state: GameState,counter = 0):
	pygame.init()
	pygame.display.set_caption(GeneralConfig.window_caption)
	window = pygame.display.set_mode((GeneralConfig.width, GeneralConfig.height))

	clock = pygame.time.Clock()

	time_elapsed_since_last_action = 0
	while game_state.run:

		game_state.event_handler()
		print(f"running {game_state.is_evolving}")

		for event in game_state.update_field_events:
			game_state.update_field_with_input(event)
			game_state.update_field_events.remove(event)

		clock.tick(GeneralConfig.fps)
		time_elapsed_since_last_action += clock.get_time()

		if game_state.is_evolving:
			if time_elapsed_since_last_action > 10:
				# start = ti.time()
				game_state.update_borders()
				game_state.evolve()
				game_state.counter = game_state.counter + 1
				game_state.edge_sync.update_edges(game_state.field.get_edges(), game_state.counter)
				# end = ti.time()
				# print(end - start)
				time_elapsed_since_last_action = 0  # reset it to 0 so you can count again

		game_state.redraw_field(window)
		pygame.display.update()
