
Asteroid = inherited("Asteroid", ActionEntity)

Network.registerClass(Asteroid)

Asteroid.variables = {
	sync = {"x", "y", "angle", "health", "dx", "dy"},
	new = {"map", "x", "y", "dx", "dy", "type", "var"},
}
Asteroid.structure = {
	sync = {"f", "f","f", "f", "f", "f"},
	new = {"e", "f", "f", "f", "f", "i", "i"},
}

function Asteroid:def()
	return ASTEROID_TYPES[self.type]
end

function Asteroid:getMass()
	return self:stat("mass")
end


function Asteroid:getRadius()
	return self:stat("radius")
end


function Asteroid:new(map, x,y, dx, dy, type, var)
	local astr = instance(self, map, map, x, y, 0, dx, dy, math.randomGaussian()*math.pi*0.1, ASTEROID_TYPES[type].health)
	astr.type = type
	astr.map = map
	astr.x = x
	astr.y = y
	astr.dx = dx or 0
	astr.dy = dy or 0
	astr.time = 0
	astr.var = math.normalize(var or 1, 1, #astr:def().sprites)
	map:addEnt(astr)
	map:addAsteroid(astr)
	return astr
end

function Asteroid:isTarget()
	return true
end

function Asteroid:remove()
	if not self._remove then
		self._remove = true
		self.map:removeEnt(self)
		self.map:removeAsteroid(self)
	end
end

function Asteroid:step(time)
	self:applyFrictionDelta(time)
	self:applyFriction(time)
	self:applyAngleAdjustment(time)
	self:applyGravity(time)
	self:super().step(self, time)
	self:applyHail(time*5)
end

function Asteroid:getStepFrequency()
	return APP.tickTime*10
end

function Asteroid:renderAt(x,y,scale,angle,a,r,g,b)
	video.renderSpriteState(self:def().sprites[self.var], x, y, scale, angle, a, r, g, b)
	
end

function Asteroid:onHit(ent, angle, impulse, counterImpulse)
	--ent:addSpeed(angle, self.dx*self:getMass()*ent:getMass(), self.dy*self:getMass()*ent:getMass())
	--self:addSpeed(angle+math.pi, -self.dx*self:getMass()*ent:getMass(), -self.dy*self:getMass()*ent:getMass())
	ent:hurt(impulse*self:stat("impulseDamageFactor")/ent:getMass())
end

function Asteroid:onDestroy()
	if self:def().subType then
		for i=1,self:def().subAmount do
			local angle = math.randomAngle()
			local rad = math.random()*self:getRadius()
			self.map.sim:create(Asteroid, self.map, self.x + math.cos(angle)*rad, self.y + math.sin(angle)*rad, self.dx + math.randomGaussian() * self:def().subSpread, self.dy + math.randomGaussian()* self:def().subSpread, ASTEROID_TYPES[self:def().subType], math.random(1,100))
		end
	end
	if self:def().resourceType then
		for i=1,self:def().resourceAmount do
			self.map.sim:create(Resource, self.map, self.map, self.x, self.y, self.dx*0.75, self.dy*0.75,RESOURCE_TYPES[self:def().resourceType])
		end
	end
end

function Asteroid:onCollided(normal, impulse, torque)
	self:bounce(normal, 0.9, impulse/self:getMass())
	local impulseDamage = impulse/self:getMass()
	if impulseDamage > self:stat("collisionThreshold") then
		local damage = impulseDamage - self:stat("collisionThreshold")
		if self:hurt(damage) then
		end
	end
end