
---- Shows an infinite amount of stackable modal windows, ----
---- with specific rendering- and behavioural functions ----
-------------------------------------------------------------------------------

Window = {
	bgdrawfunc = nil,
	fgdrawfunc = nil,
	controlfunc = nil,
	height = 0, curheight = 0,
	x = SCREEN_WIDTH2 - 150,
	doclose = false
}

function Window:open()
	for i=0, self.height, 6 do
		self.curheight = i
		self.bgdrawfunc()
		self:draw(i)
		screen.flip()
	end
end

function Window:draw(height)
	height = height or self.height
	screen.blitRotated(self.x-10, SCREEN_HEIGHT2 - height/2-4, imgs.window.border, 0)
	screen.blitRotated(self.x-10, SCREEN_HEIGHT2 + height/2, imgs.window.border, 180)
	screen:setTint(colors.white100)
	screen:textureRect(self.x, SCREEN_HEIGHT2 - height/2, 300, height, imgs.window.bg)
	screen:textureRect(self.x-8, SCREEN_HEIGHT2 - height/2, 8, height, imgs.window.fadeleft)
	screen:textureRect(self.x+300, SCREEN_HEIGHT2 - height/2, 8, height, imgs.window.faderight)
	screen.setTint()
end

function Window:show(height, bgdf, fgdf, ctrlf)
	-- Warning, deep magic (for stackable windows)
	local lowerWindow = self
	self = deepCopy(self)
	Window = self
	
	self.bgdrawfunc = bgdf or self.defaultBgDrawFunc
	self.fgdrawfunc = fgdf or NILFUNC
	self.controlfunc = ctrlf or self.defaultControlFunc
	self.height = height or 100
	self.doclose = false
	self:open()
	
	repeat
		self.bgdrawfunc()
		self:draw()
		self.fgdrawfunc()
		screen.flip()
		self.controlfunc()
	until self.doclose or globalquit
	
	for i=self.height, 0, -6 do
		self.bgdrawfunc()
		self:draw(i)
		screen.flip()
		self.curheight = i
	end
	
	Window = lowerWindow
end

function Window:showText(headline, text, bgfunc)
	local i, he = 0, 60 + Font:height(text)
	self:show(he, bgfunc,
		function()
		i = i+1
		c = Color.new(255,255,255,i*8)
		Crystal:print(headline, SCREEN_WIDTH2, SCREEN_HEIGHT2-he/2+5, Font.CENTER, c)
		Vera:print(text, SCREEN_WIDTH2, SCREEN_HEIGHT2-he/2+34, Font.CENTER, c)
		
		Vera:print("Close with Cross or Circle.", SCREEN_WIDTH2, SCREEN_HEIGHT2+he/2-16, Font.CENTER, Color.new(200,200,200,i*8))
		end)
end

function Window:close()
	self.doclose = true;
end

function Window:drawDarkRect()
	screen:fillRect(Window.x-10, SCREEN_HEIGHT2 - self.curheight/2-5, 320, self.curheight+10, colors.black100)
end


function Window.defaultBgDrawFunc()
	screen:fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, colors.clear)
	Window:drawDarkRect()
end

function Window.defaultControlFunc()
	local ctrl = Controls.read()
	if ctrl:cross() or ctrl:circle() then Window:close() end			
end
