-------------------------------
-- SSTRP
-- Author: MNWRP
--
-- init.lua
-- This file calls the rest of the script
-------------------------------

-- Define global variables
Running = false;
Loaded = false;

-- Server Includes
include( "shared.lua" ); -- Shared Functions
include( "log.lua" ); -- Logging functions
include( "error_handling.lua" ); -- Error handling functions
include( "hooks.lua" ); -- CakeScript Hook System
include( "configuration.lua" ); -- Configuration data
include( "player_data.lua" ); -- Player data functions
include( "player_shared.lua" ); -- Shared player functions
include( "player_util.lua" ); -- Player functions
include( "admin.lua" ); -- Admin functions
include( "admin_cc.lua" ); -- Admin commands
include( "chat.lua" ); -- Chat Commands
include( "daynight.lua" ); -- Day/Night and Cloc
include( "concmd.lua" ); -- Concommands
include( "util.lua" ); -- Functions
include( "charactercreate.lua" ); -- Character Creation functions
include( "items.lua" ); -- Items system
include( "schema.lua" ); -- Schema system
include( "plugins.lua" ); -- Plugin system
include( "teams.lua" ); -- Teams system
include( "client_resources.lua" ); -- Sends files to the client
include( "animations.lua" ); -- Animations
include( "doors.lua" ); -- Doors
include( "rating.lua" );

AddCSLuaFile( "scoreboard/admin_buttons.lua" )
AddCSLuaFile( "scoreboard/player_frame.lua" )
AddCSLuaFile( "scoreboard/player_infocard.lua" )
AddCSLuaFile( "scoreboard/player_row.lua" )
AddCSLuaFile( "scoreboard/scoreboard.lua" )
AddCSLuaFile( "scoreboard/vote_button.lua" )

LoadSchema( ConVars[ "Schema" ] ); -- Load the schema and plugins, this is NOT initializing.

Loaded = true; -- Tell the server that we're loaded up

function GM:Initialize( ) -- Initialize the gamemode
	
	-- My reasoning for this certain order is due to the fact that plugins are meant to modify the gamemode sometimes.
	-- Plugins need to be initialized before gamemode and schema so it can modify the way that the plugins and schema actually work.
	-- AKA, hooks.
	
	DayLog( "script.txt", "Plugins Initializing" );
	InitPlugins( );
	
	DayLog( "script.txt", "Schemas Initializing" );
	InitSchemas( );
	
	DayLog( "script.txt", "Gamemode Initializing" );
	
	InitTime();
	LoadDoors();
	
	timer.Create( "timesave", 120, 0, SaveTime );
	timer.Create( "sendtime", 1, 0, SendTime );
	
	-- SALAARIIEEESS?!?!?!?!?!?! :O
	timer.Create( "givemoney", ConVars[ "SalaryInterval" ] * 60, 0, function( )
		if( ConVars[ "SalaryEnabled" ] == "1" ) then
		
			for k, v in pairs( player.GetAll( ) ) do
			
				if( Teams[ v:Team( ) ] != nil ) then
				
					ChangeMoney( v, Teams[ v:Team( ) ][ "salary" ] );
					SendChat( v, "Paycheck! " .. Teams[ v:Team( ) ][ "salary" ] .. " credits earned." );
					
				end
				
			end 
			
		end

	end )
	
	CallHook("GamemodeInitialize");
	
	Running = true;
	
end

-- Player Initial Spawn
function GM:PlayerInitialSpawn( ply )

	-- Call the hook before we start initializing the player
	CallHook( "Player_Preload", ply );
	
	-- Send them valid models
	for k, v in pairs( ValidModels ) do
		umsg.Start( "addmodel", ply );
		
			umsg.String( v );
			
		umsg.End( );
	end
	
	-- Set some default variables
	ply.Ready = false;
	ply:SetNWInt( "chatopen", 0 );
	ply:ChangeMaxHealth(ConVars[ "DefaultHealth" ]);
	ply:ChangeMaxArmor(0);
	ply:ChangeMaxWalkSpeed(ConVars[ "WalkSpeed" ]);
	ply:ChangeMaxRunSpeed(ConVars[ "RunSpeed" ]);
	
	-- Check if they are admins
	if( table.HasValue( SuperAdmins, ply:SteamID( ) ) ) then ply:SetUserGroup( "superadmin" ); end
	if( table.HasValue( Admins, ply:SteamID( ) ) ) then ply:SetUserGroup( "admin" ); end
	
	-- Send them all the teams
	InitTeams( ply );
	
	-- Load their data, or create a new datafile for them.
	LoadPlayerDataFile( ply );

	-- Call the hook after we have finished initializing the player
	CallHook( "Player_Postload", ply );
	
	self.BaseClass:PlayerInitialSpawn( ply )
	
	
end

function GM:PlayerLoadout(ply)

	CallHook( "PlayerLoadout", ply );
	if(ply:GetNWInt("charactercreate") != 1) then
	
		if(ply:IsAdmin() or ply:IsSuperAdmin()) then ply:Give("gmod_tool"); end
		if(ply:IsAdmin() or ply:IsSuperAdmin()) then ply:Give("weapon_physgun"); end
		
		if(Teams[ply:Team()] != nil) then
		
			for k, v in pairs(Teams[ply:Team()]["weapons"]) do
			
				ply:Give(v);
				
			end
			
		end

		ply:Give("hands");
		
		ply:SelectWeapon("hands");
		
	end
	if(ply:Team() > 1) then
	ply:SetModel("models/combine_soldier.mdl")
	ply:GiveItem("smgammo")
	ply:SetSkin(2)
	end
	if(ply:Team() == 6) then
	ply:SetModel("models/combine_super_soldier.mdl")
	ply:SetSkin(2)
	end
	if(ply:Team() == 4) then
	ply:SetSkin(1)
	ply:GiveItem("buckshot")
	end
	
end

function GM:PlayerSpawn( ply )
	local rebelpos = Vector(9825.375000, 5731.062500, -127.968750)
	if(PlayerData[FormatSteamID(ply:SteamID())] == nil) then
		return; -- Player data isn't loaded. This is an initial spawn.
	end
	
	ply:StripWeapons( );
	
	self.BaseClass:PlayerSpawn( ply )
	
	GAMEMODE:SetPlayerSpeed( ply, ConVars[ "WalkSpeed" ], ConVars[ "RunSpeed" ] );
	
	if( ply:GetNWInt( "deathmode" ) == 1 ) then
	
		ply:SetNWInt( "deathmode", 0 );
		ply:SetViewEntity( ply );
		
	end
	
	-- Reset all the variables
	ply:ChangeMaxHealth(ConVars[ "DefaultHealth" ] - ply:MaxHealth());
	ply:ChangeMaxArmor(0 - ply:MaxArmor());
	ply:ChangeMaxWalkSpeed(ConVars[ "WalkSpeed" ] - ply:MaxWalkSpeed());
	ply:ChangeMaxRunSpeed(ConVars[ "RunSpeed" ] - ply:MaxRunSpeed());
	
	CallHook( "PlayerSpawn", ply )
	CallTeamHook( "PlayerSpawn", ply ); -- Change player speeds perhaps?
	if( game.GetMap() == "rp_coast_09") then
	if( ply:Team() == 1 ) then
		ply:SetPos(rebelpos)
	end
	end
	local playermodel = ply:GetModel()
	if(string.find(playermodel, "group03") != nil) then
		ply:SetArmor(100)
	end
end

function GM:PlayerSetModel(ply)
	
	if(Teams[ply:Team()] != nil) then
	
		if(Teams[ply:Team()].default_model == true) then
		
			if(Teams[ply:Team()].partial_model == true) then
			
				local m = Teams[ply:Team()]["model_path"] .. string.sub(ply:GetNWString("model"), 23, string.len(ply:GetNWString("model")));
				ply:SetModel(m);
				CallHook( "PlayerSetModel", ply, m);
				
			elseif(Teams[ply:Team()].partial_model == false) then
			
				local m = Teams[ply:Team()]["model_path"];
				ply:SetModel(m);
				CallHook( "PlayerSetModel", ply, m);
				
			end
			
		else
		
			local m = ply:GetNWString("model")
			ply:SetModel(m);
			CallHook( "PlayerSetModel", ply, m);

		end
		
	else
		
		local m = "models/kleiner.mdl";
		ply:SetModel("models/kleiner.mdl");
		CallHook( "PlayerSetModel", ply, m);
		
	end
	
	CallTeamHook( "PlayerSetModel", ply, m); -- Hrm. Looks like the teamhook will take priority over the regular hook.. PREPARE FOR HELLFIRE (puts on helmet)

end

function GM:PlayerDeath( ply, weapon, killer )
	DeathMode(ply);
	CallHook("PlayerDeath", ply);
	CallTeamHook("PlayerDeath", ply);
	for k, v in pairs( player.GetAll() ) do
	if( v:Team() > 1 ) and (ply:Team() > 1) then
		SendChat( v,  "[RADIO] BIOSIGNAL LOST FOR: " .. ply:Nick() .. "" )
	end
	end
	ply:SetNetworkedInt("next_respawn_time", CurTime() + 100)
end

function GM:PlayerDeathThink( ply )
	if ply:GetNetworkedInt("next_respawn_time") > CurTime() then
		return
	else
		ply:Spawn()
	end
end 

function GM:DoPlayerDeath( ply, attacker, dmginfo )
local activeweapon = ply:GetActiveWeapon():GetClass()
CreateItem(activeweapon, ply:GetPos() + Vector(0,0,32), Angle(0,0,0))
if(ply:Team() > 1) then
if(activeweapon == "weapon_cmbmp7") then
CreateItem("smgammo", ply:GetPos() + Vector(0,0,40), Angle(0,0,0))
end
if(activeweapon == "weapon_cmbar2") then
CreateItem("ar2ammo", ply:GetPos() + Vector(0,0,40), Angle(0,0,0))
end
if(activeweapon == "weapon_cmbsnip") then
CreateItem("sniperammo", ply:GetPos() + Vector(0,0,40), Angle(0,0,0))
end
if(activeweapon == "weapon_cmbshotgun") then
CreateItem("buckshot", ply:GetPos() + Vector(0,0,40), Angle(0,0,0))
end
if(activeweapon == "weapon_rak47") then
CreateItem("smgammo", ply:GetPos() + Vector(0,0,40), Angle(0,0,0))
end
end
end

function GM:PlayerUse(ply, entity)
	if(IsDoor(entity)) then
		local doorgroups = GetDoorGroup(entity)
		for k, v in pairs(doorgroups) do
			if(table.HasValue(Teams[ply:Team()]["door_groups"], v)) then
				return false;
			end
		end
	end
	return self.BaseClass:PlayerUse(ply, entity);
end

local DamageSounds = {
"citizen_beaten1.wav",
"citizen_beaten4.wav",
"citizen_beaten5.wav",
"cough1.wav",
"cough2.wav",
"cough3.wav",
"cough4.wav"
}

local function DamageeSounds( ply )
for k, ply in pairs( player.GetAll() ) do 
if(ply:Team() == 1 ) then
	if( ply:Health() > 50 and ply:Health() < 80 and ply:Alive() ) then
		ply:EmitSound( Sound( DamageSounds[ math.random( 1, #DamageSounds ) ] ) )
		end
	end
end
end
timer.Create("DamageSoundsAlertTimer", 5, 0, DamageeSounds)

--RESOURCES :S
resource.AddFile("materials/cmbscope/scope_lens.vmt")
resource.AddFile("materials/cmbscope/scope_lens.vtf")
resource.AddFile("materials/jaanus/ep2snip_parascope.vmt")
resource.AddFile("materials/jaanus/ep2snip_parascope.vtf")
resource.AddFile("materials/jaanus/rotatingthing.vmt")
resource.AddFile("materials/jaanus/rotatingthing.vtf")
resource.AddFile("materials/jaanus/sniper_corner.vmt")
resource.AddFile("materials/jaanus/sniper_corner.vtf")
resource.AddFile("materials/jaanus/w_sniper.vmt")
resource.AddFile("materials/jaanus/w_sniper_new.vtf")
resource.AddFile("materials/jaanus/w_sniper_new_n.vtf")
resource.AddFile("materials/jaanus/w_sniper_phong.vtf")
resource.AddFile("materials/models/weapons/v_sniper/receiver.vmt")
resource.AddFile("materials/models/weapons/v_sniper/receiver.vtf")
resource.AddFile("materials/models/weapons/v_sniper/round.vmt")
resource.AddFile("materials/models/weapons/v_sniper/round.vtf")
resource.AddFile("materials/models/weapons/v_sniper/scope.vmt")
resource.AddFile("materials/models/weapons/v_sniper/scope.vtf")
resource.AddFile("materials/models/weapons/w_sniper/sniper3.vmt")
resource.AddFile("materials/models/weapons/w_sniper/sniper3.vtf")
resource.AddFile("models/weapons/v_combinesniper_e2.mdl")
resource.AddFile("models/weapons/v_sniper.mdl")
resource.AddFile("models/weapons/w_combinesniper_e2.mdl")
resource.AddFile("models/weapons/w_sniper.mdl")
resource.AddFile("sound/jaanus/ep2sniper_empty.wav")
resource.AddFile("sound/jaanus/ep2sniper_fire.wav")
resource.AddFile("sound/jaanus/ep2sniper_reload.wav")

