local iFirstSurge = 1
local oTime = 0
iSurgeFlag = 0
bSleep = false

local tExcludedWeapons = {
	["bolt"] 			= true,
	["bolt_d1"] 		= true,
	["bolt_d2"] 		= true,
	["bolt_d3"] 		= true,
	["wpn_knife_f"] 	= true,	
	["wpn_machette_f"] 	= true,
	["grenade_rgd5_1"] 	= true, 
	["grenade_f1_1"]	= true, 
	["grenade_m61_1"]	= true,
	["grenade_gd-05_1"]	= true	
}	

local tSurgeLevel = {
	["l01_escape"]     			= 1,  
	["l02_garbage"]    			= 1,   
	["l03_agroprom"]   			= 1,
	["l03u_agr_underground"] 	= 1,	
	["l04_darkvalley"] 			= 2, 
	["l04u_labx18"] 			= 2,	
	["l05_bar"]        			= 1,   
	["l06_rostok"]     			= 2,  
	["l08_yantar"]     			= 2,
	["l08u_brainlab"] 			= 1,	
	["l07_military"]   			= 2,  
	["l10_radar"]      			= 2,
	["l10u_bunker"] 			= 1,	
	["l11_pripyat"]    			= 3,	
	["l12_stancia"]    			= 3,
	["l12_stancia_2"] 			= 3, 
	["l12u_sarcofag"] 			= 3,
	["l12u_control_monolith"]   = 3,	
	["aver"]           			= 2,
    ["generators"]     			= 3,
    ["red_forest"]     			= 2,
    ["marsh"]          			= 1,
    ["zaton"]          			= 2,
	["puzir"]              		= 2,
	["limansk"]              	= 2,
	["hospital"]             	= 3,	
    ["jupiter"]        			= 2,
    ["garbage_old"]    			= 2,
    ["predbannik"]     			= 1,
    ["yantar_old"]     			= 2,
	["pripyat"]		   			= 3,
	["warlab"] 					= 2,
	["jupiter_underground"] 	= 2
}

local tSurgeParams = {
	[1] = { 0, 0, 0.1, 0.3 },
	[2] = { 2, 4, 0.3, 0.6 },
	[3] = { 4, 9, 0.6, 1.0 }
}

function Update()
	if oTime ~= 0 and oTime:diffSec(game.get_game_time() ) < 1 and iSurgeFlag == 1 then
		if sleep_manager.is_sleep_active() then
			level.set_time_factor(TimeFactor() )
			ar_sleep.disable_scheme()
		end
		if bSleep then
			SetTime(0, 1)
			iSurgeFlag = 1
		else
			SetTime(0, 5)
			iSurgeFlag = 2
		end	
		
	elseif oTime ~= 0 and oTime:diffSec(game.get_game_time() ) < 1 and iSurgeFlag == 2 then
		if level.name() == "l05_bar" or level.name() == "l01_escape" then
			PlaySound([[ambient\siren1]])
		end
		
		local sText = "Приближается выброс. Сейчас тряхнет не по-детски, ищите норы ребята."
		SendTip("Вольный сталкер:", sText, "stalker", 10)

		if tSurgeLevel[level.name()] == 3 then
			level.set_weather("stancia")	
			level.set_weather_fx("surge_day")
		end
		
		PlaySound([[[anomaly\blowout]])
		
		SetTime(0, 6)
		iSurgeFlag = 3
		
	elseif oTime ~= 0 and oTime:diffSec(game.get_game_time() ) < 1 and iSurgeFlag == 3 then
		Step3()		
		
		SetTime(0, 3)
		iSurgeFlag = 4
		
	elseif oTime ~= 0 and oTime:diffSec(game.get_game_time() ) < 1 and iSurgeFlag == 4 then
		level.remove_cam_effector(1974)
		
		Step4()
		
		local bHided = lwc_hideout.IsInHideout()
		if not bHided then
			local tNumber = tSurgeParams[tSurgeLevel[level.name()]]
			local iRandom = math.random(tNumber[1], tNumber[2])
			for i = 1, iRandom do
				local yaw = math.pi * 2.0 * math.random()
				local iRadius = 30 * (math.random() / 2.0 + 0.5)
				local iHeight = 2.5 * math.random()
				local vPos = db.actor:position()
				local vPhantomPos = vector():set(math.sin(yaw)*iRadius+vPos.x,vPos.y+iHeight,math.cos(yaw)*iRadius+vPos.z)
				phantom_manager.spawn_phantom(vPhantomPos)
			end
		end
		
		if tSurgeLevel[level.name()] > 1 then
			bind_monster.bKillCrow = true
		end
		
		DeathBlowout()

		SetTime(0, 10)
		iSurgeFlag = 5

	elseif oTime ~= 0 and oTime:diffSec(game.get_game_time() ) < 1 and iSurgeFlag == 5 then
		level.remove_pp_effector(1001)
		level.remove_cam_effector(2004)
		level.remove_pp_effector(299)
		xr_sound.set_actor_sound("")

		local bHided = lwc_hideout.IsInHideout()
		if not bHided then
			if tSurgeLevel[level.name()] > 1 then
				level.add_cam_effector("camera_effects\\shell_shock.anm", 1974, false, "")
				PlaySound([[actor\breath_1]])
			end
		end
		level.add_pp_effector("teleport.ppe", 2009, false)
		
		PlaySound([[ambient\earthquake]])
		level.set_weather("default")
		
		if tSurgeLevel[level.name()] > 1 then
			bind_monster.bKillCrow = false
			
			local iLVid = db.actor:level_vertex_id()
			local iGVid = db.actor:game_vertex_id()
			local iOffsetX = 0
			local iOffsetZ = 0
			local iOffsetY = 100
			for i = 1, 20 do
				iOffsetX = math.random(-100, 100)
				iOffsetZ = math.random(-100, 100)
				
				local vPos = db.actor:position()
				vPos.x = vPos.x + iOffsetX
				vPos.y = vPos.y + iOffsetY
				vPos.z = vPos.z + iOffsetZ
				alife():create("m_crow", vPos, iLVid, iGVid)
			end
		end

		lwc_anomaly.Blowout()
		
		local iNextSurge = math.random(-6, 6) + iFirstSurge
		SetTime(iNextSurge)
		iSurgeFlag = 1
	end
end

function Init()
	if oTime == 0 then
		local iNextSurge = iFirstSurge + math.random(-6, 6)
		SetTime(iNextSurge)
		iSurgeFlag = 1
	end
end

function Save(packet)
	packet:w_u8(iSurgeFlag)
	if iSurgeFlag ~= 0 then
		utils.w_CTime(packet, oTime)
	end
end

function Load(reader)
	iSurgeFlag = reader:r_u8()
	if iSurgeFlag ~= 0 then
		oTime = utils.r_CTime(reader)	
	end
end

function Start()
	if iSurgeFlag > 1 and tSurgeLevel[level.name()] == 3 then
		level.set_weather("stancia")
		level.set_weather_fx("surge_day")
	end
	
	if iSurgeFlag == 4 then
		Step3()
		
	elseif iSurgeFlag == 5 then
		Step4()
	end
end

function SetTime(iH, iM, iS)
	if not iS then
		iS = 0
	end
	
	if not iM then
		iM = 0
	end

	if not iH then
		iH = 0
	end

	oTime = game.CTime()
	oTime:setHMS(iH, iM, iS)
	oTime = oTime + game.get_game_time()
end

function Step3()
	level.add_cam_effector("camera_effects\\earthquake.anm", 1974, true, "")
	level.add_pp_effector ("vibros.ppe", 1974, false)
		
	xr_sound.set_actor_sound("")
	PlaySound([[ambient\earthquake]])
	PlaySound([[anomaly\blowout]])
	PlaySounds()
end

function Step4()
	local bHided = lwc_hideout.IsInHideout()
	if not bHided then
		PlaySound([[actor\pain_3]])
		
		if tSurgeLevel[level.name()] > 1 then
			xr_sound.set_actor_sound("level_border_detector")
			xr_sound.set_actor_sound_factor(0.01)
		end
		
		level.add_cam_effector("camera_effects\\head_shot.anm", 1975, false, "")			
		level.add_cam_effector("camera_effects\\fatigue.anm", 2004, true, "")
		level.add_pp_effector("yantar_underground_psi.ppe", 299, true)
		level.set_pp_effector_factor(299, 1.0)
	end
end

function PlaySounds()
	local iRandom = math.random(1, 4)
	local sSound = [[ambient\random\rnd_the_horror1]]
	if iRandom == 1 then 
		sSound = [[ambient\rnd_outdoor\rnd_dark4]]
	elseif iRandom == 2 then
		sSound = [[ambient\rnd_outdoor\rnd_moan1]]
	elseif iRandom == 3 then
		sSound = [[ambient\rnd_outdoor\rnd_moan2]]
	elseif iRandom == 4 then
		sSound = [[ambient\rnd_outdoor\rnd_dark6]]
	end
	PlaySound(sSound) 
end

function DeathBlowout()
    local oActor = db.actor	
	local bHided = lwc_hideout.IsInHideout()
	local tNumber = tSurgeParams[tSurgeLevel[level.name()]]
	local iFactor = math.random(tNumber[3], tNumber[4])	
	
	if not bHided then
		if tSurgeLevel[level.name()] > 1 then
			level.add_cam_effector("camera_effects\\fusker.anm", 959, false, "")
		end
		
		local oActiveItem = db.actor:active_item()
		if oActiveItem and not tExcludedWeapons[oActiveItem:section()] then
			db.actor:drop_item(oActiveItem)
		end
	
        oActor.health = iFactor * -0.8	
        oActor.power  = iFactor * -0.8
        oActor.radiation = iFactor * 0.6
        oActor.psy_health = iFactor * -0.6
        oActor.morale = iFactor * -0.6
	else
        oActor.health = iFactor * -0.4	
        oActor.power  = iFactor * -0.4
        oActor.radiation = iFactor * 0.3
        oActor.psy_health = iFactor * -0.3
        oActor.morale = iFactor * -0.3
    end
end	