local sti = require"./Simple-Tiled-Implementation/sti"

function love.load()
--love.window.updateMode( 320, 320)

	love.window.setTitle("red man goes dancing")

	source = love.audio.newSource( "audio/ramesesb-deeper.mp3", "static")
	source:setLooping(true)
	source:play()

	-- load map
	map = sti("map/map.lua")

	-- create sprites layer
	local layer = map:addCustomLayer("sprites", 3)

	-- get player spawn object
	local player
	for k, object in pairs(map.objects) do
		if object.name == "player" then
			player = object
			break
		end
	end

	-- create player object
	local sprite = love.graphics.newImage("img/sprite.png")
	layer.player = {
		sprite	= sprite,
		x	= player.x,
		y	= player.y,
		ox	= sprite:getWidth() / 2,
		oy	= sprite:getHeight() / 1
	}

	-- add controls
	layer.update = function(self, dt)
		local speed = 72 

		if love.keyboard.isDown("w") or love.keyboard.isDown("up") then
			self.player.y = self.player.y - speed * dt
		end
		if love.keyboard.isDown("s") or love.keyboard.isDown("down") then
			self.player.y = self.player.y + speed * dt
		end
		if love.keyboard.isDown("a") or love.keyboard.isDown("left") then
			self.player.x = self.player.x - speed * dt
		end
		if love.keyboard.isDown("d") or love.keyboard.isDown("right") then
			self.player.x = self.player.x + speed * dt
		end
	end

	-- draw player
	layer.draw = function(self)
		love.graphics.draw(
			self.player.sprite,
			math.floor(self.player.x),
			math.floor(self.player.y),
			0,
			1,
			1,
			self.player.ox,
			self.player.oy
		)

		-- temp
		love.graphics.setPointSize(5)
		love.graphics.points(math.floor(self.player.x), math.floor(self.player.y))
	end

	map:removeLayer("spawn point")
end

function love.update(dt)
	map:update(dt)
end

function love.draw()
	coloredtext = { 
		{255,0,0,255}, "OBJECTIVE: keep dancing and dont float off into space" 
	}
	
	-- scale world
	local scale = 2
	local screen_width = love.graphics.getWidth() / scale
	local screen_height = love.graphics.getHeight() / scale
	
	-- translate world for centering player
	local player = map.layers["sprites"].player
	local tx = math.floor(player.x - screen_width / 2)
	local ty = math.floor(player.y - screen_height / 2)
	
	map:draw(-tx, -ty, scale)
	
	love.graphics.polygon('fill', 20, 20, 720, 20, 720, 85, 20, 85)
	love.graphics.print(coloredtext, 36, 36, 0, 2, 2)
end

