local MOB_DELAY = 315
local MOB_DELAY_RANDOM = 140

local EpicWorldFullMoon = Class(function(self, inst)
	self.inst = inst
	self.mobspawndelay = MOB_DELAY + math.random(0,MOB_DELAY_RANDOM)
	self.randommob = nil
	self.inst:StartUpdatingComponent(self)
end)

function EpicWorldFullMoon:OnUpdate()
	if(GetClock():IsNight() and GetClock():GetMoonPhase() == "full") then
		self:SpawnMob()
	end
end

function EpicWorldFullMoon:GetFloorSpawnPoint(pt, radius)
    local theta = math.random() * 2 * PI
	local offset = FindWalkableOffset(pt, theta, radius, 12, true)
	if offset then
		local pos = pt + offset
		local ground = GetWorld()
	    local tile = GROUND.GRASS
	    if ground and ground.Map then
	        tile = self.inst:GetCurrentTileType(pos:Get())
	    end
		return pos
	end
end

function EpicWorldFullMoon:SpawnMob()
	self.mobspawndelay = self.mobspawndelay - 1
	if self.mobspawndelay == 0 then
		local sound = CreateEntity()
		sound.entity:AddTransform()
		sound.entity:AddSoundEmitter()
		sound.persists = false
		local sm = GetSeasonManager()
		local pt = Vector3(GetPlayer().Transform:GetWorldPosition())
		local spawn_pt = self:GetFloorSpawnPoint(pt,30)
		if spawn_pt then
			local pos = Vector3(GetPlayer().Transform:GetWorldPosition())
			local ground = GetWorld()  
			local tile = ground.Map:GetTileAtPoint(pos.x, pos.y, pos.z)
			local chance = math.random(1,25)
			local new_spawn_pt = self:GetFloorSpawnPoint(pt,30)
			if new_spawn_pt then
				if chance == 25 then
					self.randommob = SpawnPrefab("warg")
				elseif chance >= 15 and chance < 25 then
					self.randommob = SpawnPrefab("ughost")
				elseif chance >= 12 and chance < 15 then
					self.randommob = SpawnPrefab("hound")
				elseif chance >= 10 and chance < 12 then
					self.randommob = SpawnPrefab("icehound")
				elseif chance >= 5 and chance < 10 then
					self.randommob = SpawnPrefab("beardlord")
				elseif chance < 5 then
					self.randommob = SpawnPrefab("pigman")
					self.randommob.components.werebeast:TriggerDelta(8)
				end
				self.randommob.Physics:Teleport(new_spawn_pt:Get())
				if chance == 25 then
					self.mobspawndelay = 8400
				else
					self.mobspawndelay = MOB_DELAY + math.random(0,MOB_DELAY_RANDOM)
				end
				print("FullMoon succes!")
			else
				print("FullMoon failed!")
				self.mobspawndelay = 1
			end
		else
			print("FullMoon failed!")
			self.mobspawndelay = 1	
		end
	end
end

return EpicWorldFullMoon