Planet = Object.extend(Object)

function Planet:new()
	Planet.super.new(self)
end

function Planet:init()
	self.canvas = love.graphics.newCanvas(windowWidth, windowHeight)

	self.map = {
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
	}

	self.spritemap = {
		s1= tileGroundFull
	}

	self.hasGeneratedMap = false

	self.mapThread = love.thread.newThread("planet/mapthread.lua")
	self.mapThread:start()
	self.channel = {}
	self.channel.tomap = love.thread.getChannel("tomap")
	self.channel.blocks = love.thread.getChannel("blocks")

	self:generateMapBlock()
end

function Planet:update(dt)
	local error = self.mapThread:getError()
	assert( not error, error )

	local blocks = self.channel.blocks:pop()
	if blocks then
		for y = 1, table.getn(blocks) do
			table.insert(self.map, blocks[y])
		end

		self:draw()
		self.hasGeneratedMap = true
	end
end

function Planet:draw()
	local maplen = table.getn(self.map)
	if maplen > 0 then
		love.graphics.setCanvas(self.canvas)
		love.graphics.setColor(1,1,1,1)

		local sprite = nil
		local pos = 0
		for y=1, math.min(maplen,20) do
			for x=1, 25 do
				sprite = nil
				pos = self.map[y][x]
				if pos > 0 then
					sprite = self.spritemap["s"..pos]
					love.graphics.draw(sprite, (x-1)*32, (600-98) - (y-1)*32)
				end
			end
		end

		love.graphics.setCanvas()
	end
end

function Planet:generateMapBlock()
	self.channel.tomap:push( { message= "generateblock", width= 25, height= 60 } )
end