love.graphics.setDefaultFilter("linear", "nearest")

local utf8 = require("utf8")
class = require "libs/middleclass"
Timer = require "libs/hump/timer"
sfxr = require "libs/sfxrlua/sfxr"
require "libs/TSerial"
require "_debug_helpers"
require "_helpers"
require "input"
require "color"
require "room"
require "shaders"
require "sprite_manager"
require "level_editor/editor"

function love.load()
	globalAssetProperties = TSerial.unpack(love.filesystem.read("assets.prop") or "{}")

	_initDefaults()
	_initGridVars()
	_initSounds()
	_initGlobalColors()
	_initLevelEditor()


	processSprites()

	gameCanvas = love.graphics.newCanvas()
	sideBarCanvas = love.graphics.newCanvas(sideBarBox.w, sideBarBox.h)
	finalCanvas = love.graphics.newCanvas()


	inputTimer = Timer.new()

	currentRoom = Room:new{
		name = "start" -- TEMP: load a migrated level to eyeball it; revert once the room picker lands
	}

	response = ""
end

function love.update(dt)
	Input:handler(dt)
	currentRoom:update(dt)

	-- if love.keyboard.isDown("w") then worldSha = worldSha + 1 end
	-- if love.keyboard.isDown("s") then worldSha = worldSha - 1 end
end

function love.draw()
	love.graphics.setCanvas(gameCanvas)
	love.graphics.clear()
	love.graphics.setBlendMode("screen")
	currentRoom:draw()

	love.graphics.setCanvas(finalCanvas)
	love.graphics.clear()

	local scaleCoefficient = .93
	local samples = 7
  	
  	love.graphics.push()

	for i = 1, samples do
		local c = 65 / (i * 1.75)
		love.graphics.setColor(c, c, c)
		love.graphics.scale(scaleCoefficient, scaleCoefficient)
		love.graphics.translate((width / 2 - (width * scaleCoefficient) / 2) + 2, (width / 2 - (height * scaleCoefficient) / 2) + 2)
		love.graphics.draw(gameCanvas, 0, 0)
	end

	love.graphics.pop()
	love.graphics.setColor(255, 255, 255)
	love.graphics.draw(gameCanvas, 0, 0)
	love.graphics.setCanvas()

	love.graphics.setCanvas(sideBarCanvas)
	love.graphics.clear()
	editorDraw()
	love.graphics.setCanvas()

	love.graphics.setBlendMode("alpha")
	love.graphics.setColor(255, 255, 255, 255)
	love.graphics.draw(finalCanvas, 0, 0)
	love.graphics.draw(sideBarCanvas, sideBarBox.x, sideBarBox.y)
	love.graphics.print("Current FPS: "..tostring(love.timer.getFPS( )), 10, 10)

end

function love.keypressed(key)
	if Input.isPlayerMove(key) then
		currentRoom:movePlayer(key)
	elseif Input.isPlayerSwitch(key) then
		local c = Input.playerColor(key)
		currentRoom:switchPlayerColor(c)
	end

	-- if key == "w" then
	-- 	worldSha = worldSha + 1
	-- end
	-- if key == "s" then
	-- 	worldSha = worldSha - 1
	-- end

	if key == "return" then
		response = ""
		editorCompleteResponse()
	elseif key == "backspace" then
        local byteoffset = utf8.offset(response, -1)

        if byteoffset then
            -- remove the last UTF-8 character.
            -- string.sub operates on bytes rather than UTF-8 characters, so we couldn't do string.sub(response, 1, -2).
            response = string.sub(response, 1, byteoffset - 1)
            editorTextHandler(response)
        end
	end
end

function love.mousepressed(x, y, button)
	if button == 2 then
		currentRoom:attemptDelete(x, y, selectedColor)
	end
	editorMouseHandler(x, y, button)
end

function love.textinput(t)
	response = response .. t
	editorTextHandler(response)
end

function _initDefaults()
	--set filter
	love.graphics.setDefaultFilter("linear", "nearest")
	love.filesystem.createDirectory("rooms")
	
	--set global width / height variables
	width = love.graphics.getWidth()
	height = love.graphics.getHeight()
	if width > height then
		width = height
	else
		height = width
	end

	--set randomseed
	math.randomseed(os.time())

	--font
	font = love.graphics.newFont("font/LCD_Solid.ttf", 16)
	love.graphics.setFont(font)

	--sidebar
	sideBarBox = {x = width, y = 0, w = love.graphics.getWidth() - width, h = height}
end

function _initGridVars()
	gridWidth, gridHeight = 11, 11
	drawScale = width / gridWidth / 16

	worldSha = 1
end

function _initGlobalColors()
	gColor = {}
	gColor.red, gColor.green, gColor.blue, gColor.white = Color:new("red"), Color:new("green"), Color:new("blue"), Color:new("white")
end

function _initSounds()
	staticWave = sfxr.newSound()
	staticWave.wavetype = 3
	staticWave.frequency.start = .1
	staticWave.envelope.release = 0
	staticWave.envelope.sustain = 1
	staticWave.envelope.decay = 0
	static = love.audio.newSource((staticWave:generateSoundData()))
	static:setLooping(true)
	static:setVolume(.15)
	static:play()
end

