#include "script/common.lua"
#include "script/explosion.lua"


function init()
	timer = 0
	body = FindBody("lightning")
	sound = LoadSound("thunder-strike.ogg")
	transform = GetBodyTransform(body)

	shapes = GetBodyShapes(body)
	
	--Move lightning out of sight
	emissive = 0
	SetBodyTransform(body, Transform(Vec(0,10000,0)))
	setEmissive(0)
	
	done = false
	
	lightning_timer = 0
	lightning_wait_timer = 1
	lightning_waiting = true
	lighting_ready = false
end


function setEmissive(value)
	for i=1,#shapes do
		SetShapeEmissiveScale(shapes[i], value)
	end
end

function tick(dt)
	if not lightning_waiting then
		lightning_wait_timer = math.random(20, 60)
		lightning_waiting = true
		lightning_timer = 0
	end
	
	if lightning_waiting and not lighting_ready then 
		lightning_timer = lightning_timer + dt
		if lightning_timer > lightning_wait_timer then
			lighting_ready = true
			lightning_timer = 0
		end
	end
		
	if not done and lighting_ready then
		local random_x = math.random(-100,90)
		local random_z = math.random(-100,120)
		local y_pos = 23.7
		local rotation = QuatEuler(0, math.random(-18,18) , 0)
		local ligtning_transform = Transform(Vec(random_x, y_pos, random_z), rotation)
		lightning_strike(ligtning_transform)
	else
		if timer > 0 then
			timer = timer - dt
			if timer <= 0 then
				SetBodyTransform(body, Transform(Vec(0,10000,0)))
				setEmissive(0)
				lighting_ready = false
				lightning_waiting = false
				done = false
			else
				emissive = clamp(emissive + math.random(-10,10)*0.1, 0.1, 1.0)
				setEmissive(emissive)
			end
		end
	end
	
	
end

function lightning_strike(ligtning_transform)
	timer = 0.7
	SetBodyTransform(body, ligtning_transform)
	emissive=1

	local playerpos = GetPlayerPos()
	local soundstrength = 45/(VecLength(VecSub(Vec(playerpos[1], 23, playerpos[3]), ligtning_transform.pos)))
	PlaySound(sound, GetPlayerPos(), soundstrength)
	done = true
end