# Imports
import pygame
import pickle
from os import path
# Set Up
pygame.init()
fps = 60
clock = pygame.time.Clock()
tile_size = 48
cols = 35
margin = 100
screen_width = tile_size * cols
screen_height = 900 + margin
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Level Editor')
clicked = False
level = 1
white = (255, 255, 255)
black = (0, 0, 0)
font = pygame.font.SysFont('Futura', 24)
#load images
background = pygame.image.load('images/background_editor.png')
left = pygame.image.load("images/left.png")
middle = pygame.image.load('images/middle.png')
right = pygame.image.load("images/right.png")
water = pygame.image.load('images/water1.png')
enemy = pygame.image.load('images/enemy.png')
door = pygame.image.load('images/door.png')
button_save = pygame.image.load('images/button_save.png')
button_load = pygame.image.load('images/button_load.png')
button_exit = pygame.image.load("images/button_exit.png")
# Create Empty World
world_data = []
for row in range(35):
	r = [0] * 35
	world_data.append(r)
# Output Text
def draw_text(text, font, text_col, x, y):
	img = font.render(text, True, text_col)
	screen.blit(img, (x, y))
# Grid
def draw_vertical():
	for c in range(36):
		# Vertical Lines
		pygame.draw.line(screen, white, (c * tile_size, 0), (c * tile_size, screen_height - margin -36))
def draw_horizontal():
	for c in range(19):
		# Horizontal Lines
		pygame.draw.line(screen, white, (0, c * tile_size), (screen_width, c * tile_size))
# Draw World
def draw_world():
	for row in range(18):
		for column in range(35):
			if world_data[row][column] > 0:
				# Left
				if world_data[row][column] == 1:
					image = pygame.transform.scale(left, (tile_size, tile_size))
					screen.blit(image, (column * tile_size, row * tile_size))
				# Middle
				elif world_data[row][column] == 2:
					image = pygame.transform.scale(middle, (tile_size, tile_size))
					screen.blit(image, (column * tile_size, row * tile_size))
				# Right
				if world_data[row][column] == 3:
					image = pygame.transform.scale(right, (tile_size, tile_size))
					screen.blit(image, (column * tile_size, row * tile_size ))
				# Water
				elif world_data[row][column] == 4:
					image = pygame.transform.scale(water, (tile_size, tile_size))
					screen.blit(image, (column * tile_size, row * tile_size))
				# Enemy
				if world_data[row][column] == 5:
					image = pygame.transform.scale(enemy, (tile_size, int(tile_size * 0.75)))
					screen.blit(image, (column * tile_size, row * tile_size + (tile_size * 0.25)))
				# Door
				if world_data[row][column] == 6:
					image = pygame.transform.scale(door, (tile_size, int(tile_size * 0.75)))
					screen.blit(image, (column * tile_size, row * tile_size + (tile_size * 0.25)))
# Button Class		
class Button():
	# Init
	def __init__(self, x, y, image):
		self.image = image
		self.images = pygame.transform.scale(image, (100,55))
		self.rect = self.images.get_rect()
		self.rect.topleft = (x, y)
		self.clicked = False
	# Draw
	def draw(self):
		self.clicked = False
		pos = pygame.mouse.get_pos()
		if self.rect.collidepoint(pos):
			if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
				self.clicked = True
		screen.blit(self.images, (self.rect.x, self.rect.y))
		return self.clicked
# Scale and Initialise Classes
background = pygame.transform.scale(background, (1750,865))
load_button = Button(screen_width // 2 - 330, screen_height - 95, button_load)
save_button = Button(screen_width // 2 - 50, screen_height - 95, button_save)
exit_button = Button(screen_width // 2 + 250, screen_height - 95, button_exit)
# Game Loop
run = True
while run:
	# Clock
	clock.tick(fps)
	# Background
	screen.fill(black)
	screen.blit(background, (0, 0))
	# Grid
	draw_vertical()
	draw_horizontal()
	draw_world()
	#text showing current level
	draw_text(f'Level: {level}', font, white, tile_size, screen_height - 80)
	draw_text('Press W or S to change level', font, white, tile_size, screen_height - 60)
	# Load Button
	if load_button.draw():
		#load in level data
		if path.exists(f'levels/custom/level_{level}'):
			pickle_in = open(f'levels/custom/level_{level}', 'rb')
			world_data = pickle.load(pickle_in)
		else:
			pickle_out = open(f'levels/custom/level_{level}', 'wb')
			pickle.dump(world_data, pickle_out)
			pickle_out.close()
	# Save Button
	if save_button.draw():
		pickle_out = open(f'levels/custom/level_{level}', 'wb')
		pickle.dump(world_data, pickle_out)
		pickle_out.close()
	# Exit Button
	if exit_button.draw():
		run = False
	# Event Handler
	for event in pygame.event.get():
		# Quit Game
		if event.type == pygame.QUIT:
			run = False
		# Clicks To Chnage Tiles
		if event.type == pygame.MOUSEBUTTONDOWN and clicked == False:
			clicked = True
			mouse_position = pygame.mouse.get_pos()
			x = mouse_position[0] // tile_size
			y = mouse_position[1] // tile_size
			# Check That The Coordinates Are Within The Tile Area
			if x < 35 and y < 18:
				# Update Tile Value
				if pygame.mouse.get_pressed()[0] == 1:
					world_data[y][x] += 1
					if world_data[y][x] > 6:
						world_data[y][x] = 0
				elif pygame.mouse.get_pressed()[2] == 1:
					world_data[y][x] -= 1
					if world_data[y][x] < 0:
						world_data[y][x] = 6		
		if event.type == pygame.MOUSEBUTTONUP:
			clicked = False
		# Change Level
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_w:
				level += 1
			elif event.key == pygame.K_s and level > 1:
				level -= 1
	#update game display window
	pygame.display.update()
# Quit Pygame
pygame.quit()