
--===================================================
--									
--								GHI Area Sound
--								ghi_areaSound.lua
--
--						Handling of area sounds
--	
-- 						(c)2011 The Gryphonheart Team
--								All rights reservated
--===================================================

local class;
function GHI_AreaSound()
	if class then
		return class;	
	end
	
	class = GHClass("AreaSound");
	local position = GHI_Position();
	local comm = GHI_Comm();
	local RecieveAreaSound;
	local MAX_RANGE = 50;
	
	class.Send = function(soundPath,range,delay)
		local soundData = {	
			soundPath = soundPath,
			delay=delay or 0,
		};	
		
		local playerPos = position.GetPlayerPos();
		
		local players = GHI_AddOns:GetAllPlayers()
		for _,player in pairs(players) do
			comm.Send(nil,player,"AreaSound",playerPos,range or 0,soundData)
		end			
	end
	
	RecieveAreaSound = function(sender,playerPos,range,data,...)
		if GHI_MiscData["block_area_sound"] then 
			return 
		end
		
		if playerPos.continent > 0 and position.IsPosWithinRange(playerPos,min(range,MAX_RANGE)) then
			local soundPath = gsub(data.soundPath,"\\\\","/");
			soundPath = gsub(soundPath,"\\","/");
			soundPath = (string.match(soundPath,"[a-zA-z0-9\\/_.%s]*"));
				
				local suffix = "";
				if GHI_MiscData["show_area_sound_sender"] then
					suffix = " GHI_Message(\"Area sound by "..(sender or "nil").."\");"
				end
				local a = "PlaySoundFile(\""..soundPath.."\");"..suffix;
				GHI_DoScript(a,tonumber(data.delay or 0));
		end		
	end
	comm.AddRecieveFunc("AreaSound",RecieveAreaSound);
	
	return class;
end